Search code examples
javascriptmocha.jsecmascript-2016

what is a good practice to change the default timeout globally or for one test only? mocha


I am using before hook with try catch block for calling some functionality inside my try block. So before block runs before each it.

describe('Function response', ()=> {
  // this.timeout(5000); //here
  let response;
  before(async () => {
   // this.timeout(500000); //or here
    try {
      response = await myFunction(argument);
    } catch (err) {
      assert.fail(err);//seems doesn't work
    }
  });
  it('function response to be an array', () => {
    expect(response).to.be.an('array');
  });
});

I am getting this error

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

After opening one of the comments that change default timeout after of course making arrow functions to regular, the test works as expected.
I would like to know what is the best practice. Maybe it's better to change the default timeout in test script?

"test": "mocha -r ts-node/register src/**/*.spec.ts --timeout 5000

Also maybe I am not handling the error in catch block correctly?


Solution

  • Best practice is to set the timeout at the needed scope:

    describe('something', function() {
      this.timeout(100);  // sets the timeout for everything in "describe"
    
      before(function(done) {
        this.timeout(500);  // sets the timeout ONLY for "before"
        setTimeout(done, 450);  // <= this works
      });
    
      it('should do something', function (done) {
        setTimeout(done, 150);  //  <= this times out
      });
    });
    
    • If you need a particular timeout for all your tests, then set it at the global level
    • If you need a particular timeout for everything within a describe, set it in the describe
    • If you need a particular timeout for one before, it, etc., set it in that function