How to avoid timeouts in mocha testcases?

In mocha a default timeout of 2 seconds (2000ms) is set by default.

You can extend the default (global) timeout from the command line using the --timeout xxxx flag.

If you want instead to change the timeout for a specific test case you can use the this.timeout( xxxx ) function - note it does not work for arrow functions - (where xxxx is a number like 20000 representing milliseconds).

it('My test', function(){
  this.timeout(5000);
  //... rest of your code
});

You can also set a timeout of a set of test cases (wrapped by a describe):

describe("My suite", function(){
  // this will apply for both "it" tests
  this.timeout(5000);

  it( "Test 1", function(){
     ...
  });

  it( "Test 2", function(){
     ...
  });

});

It also works for before, beforeEach, after, afterEach blocks.

More documentation is available here: https://mochajs.org/#timeouts

Consider that 2 seconds is usually a good amount of time to run your tests so I would say that extend the default timeout should be an exception, not the common rule in your tests. Also if your test is not async and you have to extend the timeout I would strongly suggest to review the function that is taking so long before extending the timeout.


Mocha : Timeouts

Test-specific timeouts may also be applied, or the use of this.timeout(0) to disable timeouts all together:

To disable the timeout from happening simply set it to 0. I use mocha <file> --timeout 0 when I'm debugging so the timeout error does not get thrown.


If I am running my testcases with mocha command then its show this error while If I am running test mocha --timeout 15000 then testcase is passing correctly. But I want to avoid timeout, How can I do that?

You can't avoid timeouts, since it looks like you're testing a remote service. If, for whatever reason, the request to that service takes a long time, you will run into timeouts.

You can tell Mocha to disable for timeout checking by setting the timeout to 0, but that's probably also not ideal because it may cause each test case to take an excessive amount of time.

As an alternative, you can mock request (which I assume is superagent) so you can control the entire HTTP request/response flow, but since it looks like you're testing a remote service (one which you have no control over) that would make this particular test case moot.