1
votes

I have a simple test with an assertion contained in a setTimeout function as follows:

  it('asserts after timeout', (done) => {
    setTimeout(() => {
      expect(1).to.be.equal(1);
      done();
    }, 500);
  });

However I'm getting the following error:

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

2
May be you need a try catch and put done() inside catch.. The timeout of 2000 may be for the entire page/app..estinamir

2 Answers

1
votes

After banging my head around and looking at every unit test in the code base, I realized there was a call to sinon.useFakeTimers(); Removing that fixed the issue.

0
votes

Your example should work. However you'll get that error when the expectation fails. For this, wrap your setTimeout in a Promise and ensure that you call done in the next then method.

It's considered bad practice because of this to put the done method in the same area as what you're testing.

it('asserts after timeout', (done) => {
    (new Promise((resolve,reject)=>{
       setTimeout(() => {
         resolve();
       }, 500);
    }))
    .then(()=>expect(1).to.be.equal(1))
    .then(()=>done(), done);
});