简体   繁体   English

在 mocha 测试中使用 done 和 setTimeout 的简单示例未按预期工作

[英]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:我有一个包含在 setTimeout 函数中的断言的简单测试,如下所示:

  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.错误:超过 2000 毫秒超时。 For async tests and hooks, ensure "done()" is called;对于异步测试和钩子,确保调用“done()”; if returning a Promise, ensure it resolves.如果返回 Promise,请确保它已解决。

After banging my head around and looking at every unit test in the code base, I realized there was a call to sinon.useFakeTimers();在我仔细查看代码库中的每个单元测试之后,我意识到有一个对 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.为此,请将您的setTimeout包装在Promise并确保您在下一个 then 方法中调用done

It's considered bad practice because of this to put the done method in the same area as what you're testing.done方法放在与您正在测试的区域相同的区域中被认为是bad practice

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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