对于异步测试和挂钩,确保调用"done()"; 如果返回Promise,请确保它已解决

Ger*_*gen 27 mocha.js node.js

我在测试时对nodejs进行了测试,我得到了未声明的完成函数的错误.

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

我的测试代码是,我已完成回调但仍然收到错误来调用 done();

    it('remove existing subdocument', (done) => {
    const Vic = new User({
      name: 'Vic',
      posts: [{ title: 'Leaning Nodejs' }]
    });

    vic.save()
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        const post = user.posts[0];
        post.remove();
        return user.save();
      })
      .then(() => User.findOne({ name: 'Vic' }))
      .then((user) => {
        assert(user.posts.length === 0);
        done();
      });
  });
Run Code Online (Sandbox Code Playgroud)

avc*_*vck 24

我面临同样的问题,@ MFAL的评论链接有所帮助.我正在扩展它.

当出现错误/错误断言时,会在promise中引发错误.这导致承诺拒绝.一旦拒绝完成,从未调用过,mocha报告超时.我通过编写一个.catch块并将其与承诺链接来解决这个问题:

          it('resolves', (done) => {
            fooAsyncPromise(arg1, arg2).then((res, body) => {
                expect(res.statusCode).equal(incorrectValue);
                done();
            }).catch(done);
         });
Run Code Online (Sandbox Code Playgroud)

Wietse博客中提到的其他方式是:

链接一个then(done, done)处理承诺的解决和拒绝.

         it('resolves', (done) => {
           resolvingPromise.then( (result) => {
             expect(result).to.equal('promise resolved');
           }).then(done, done);
         });
Run Code Online (Sandbox Code Playgroud)

回报承诺:

        it('resolves', () => {
          return resolvingPromise.then( (result) => {
            expect(result).to.equal('promise resolved');
          });
        });
Run Code Online (Sandbox Code Playgroud)

使用异步/等待:

        it('assertion success', async () => {
          const result = await resolvingPromise;
          expect(result).to.equal('promise resolved'); 
        });
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用 async/await,但在使用“@open-wc/testing”和 Karma 测试 LitElement Web 组件时仍然遇到此问题。不过,直到我的最新组件为止,我都没有遇到任何问题。。。。我想知道差异化因素是什么。 (10认同)

Sab*_*esh 20

我知道一种丑陋的做法,只需将Mocha的默认超时从 2秒增加到10秒,这可以通过在测试脚本中添加标志--timeout 10000来完成,即 -

的package.json

 "scripts": {
    "start": "SET NODE_ENV=dev && node server.js",
    "test": "mocha --timeout 10000"
  }
Run Code Online (Sandbox Code Playgroud)

  • 这个对我有用,我没有更改任何代码,我的测试突然开始无缘无故地失败。与昨天相比,我的机器可能只是变慢了? (2认同)

Aji*_*nju 13

您可以将超时添加到特定测试以增加/覆盖默认超时 2 秒。我遇到了同样的问题,但能够使用以下方法绕过它:

it('Test', (done) => { 
//your code  
done();
}).timeout(10000);
Run Code Online (Sandbox Code Playgroud)

  • 错误:解决方法指定过多。指定回调*或*返回 Promise;不是都。 (3认同)

ela*_* BA 10

我的问题是超时本身(延长它没有帮助)所以我的解决方案是

it("it should test methods",function(){
     this.timeout(0);
   });
Run Code Online (Sandbox Code Playgroud)

如你所见,你不需要done争论


小智 5

如果以上都没有帮助,请尝试摆脱“完成”并使用 async function() 代替

it("Test Post Request", async function () {
    _code_
})
Run Code Online (Sandbox Code Playgroud)