mocha: Error: Timeout of 2000ms exceeded

When I try to use promises with mocha, I’m getting the error below:

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

Actually, I’m trying to retireve data from a remote server. Mocha won’t wait until the promise has been resolved or rejected.


function fn(){
  return new Promise((resolve, reject) => {
       setTimeout(() => resolve({foo:'bar'}),7000);
  })
}

 it('should retrieve data',function(done){
            fn().then((res) => done()).catch((err) => done(err));
 });

After 2 seconds, this error occurs. I’ve been planning to check the returning data within then and call the assert.

it('should retrieve data',function(done){
   fn().then(() => {
       assert(true)
       done()
   });
});

What am I doing wrong? I want to check the returning data if it has proper keys, etc.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (4 by maintainers)

Most upvoted comments

For the people who still struggling with this problem, just add this.enableTimeouts(false) may solve it. Example:

describe('Test', function () {
  this.enableTimeouts(false)
  // your code here
}

You can may also try to run the code last. I had the same issue but was able to by pass it using: after('Test', (done) => { //your code });

If it is expected/acceptable for your test to take longer than the timeout specified in the error message, you can override the amount of time for the timeout using this.timeout(<maximum acceptable time>) or --timeout <maximum acceptable time>.

P.S. You can remove done from the tests and return fn().then(... instead, Mocha will treat promise resolution as success and rejection as failure.

:neckbeard: Other option, you can use de TIMEOUTS suite, check this example:

describe('a suite of 7 seconds', function () {
  this.timeout(7500);
  it('should take less than 5s', function (done) {
    setTimeout(done, 5000);
  });

  it('should take less than 2s as well', function (done) {
    setTimeout(done, 2000);
  });
});

More info: 👉 https://mochajs.org/#timeouts