Ajay Sabarish
Ajay Sabarish

Reputation: 71

What does this.timeout() do in a mocha test?

I am new to javascript, I would like to know what does this.timeout() do in this mocha test.

it('TestConnect', async function() {
    this.timeout(40000);
});

Upvotes: 0

Views: 2655

Answers (2)

J.F.
J.F.

Reputation: 15177

In mocha, timeout is the maximum time test will wait for done before set test as failed.

So, for example, your timeout is 5000 (5 seconds) and the code has a loop that spent 7 seconds to iterate over all object. Then the test will fail even data is ok because timeout is triggered before done() is called.

Is true not exists a great explanation, but in this docs is defined as:

Sets timeout threshold value.

Threshold is the time when you decide test should fail.

Upvotes: 0

Njuguna Mureithi
Njuguna Mureithi

Reputation: 3856

Consider the following example:

describe('a suite of tests', function() {
  this.timeout(500);

  it('should take less than 500ms', function(done) {
    setTimeout(done, 600); // fails
  });

  it('should take less than 500ms as well', function(done) {
    setTimeout(done, 250); // passes
  });
});

I already looked into it, it says how to set timeouts, but didn't explain what is a timeout. Does the program exit after specified number of seconds or does the program wait for specified number of seconds before executing ?

The program doesn't necessarily exit, but the above (example) suite fails. The timeout parameter just means that tests in that suite, or a specific test that it has to call done within the timeout period else the test fails.

Upvotes: 1

Related Questions