简体   繁体   中英

Simple example using done and setTimeout inside a mocha test not working as expected

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.

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.

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM