【问题标题】:Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" when using Mocha for test in nodejs错误:超过 2000 毫秒的超时。对于异步测试和钩子,在 nodejs 中使用 Mocha 进行测试时确保“done()”
【发布时间】:2020-10-23 10:03:53
【问题描述】:

我想为 test createUser 写一个测试。

我写了这段代码:

const User = require("../src/Entite/User");

describe("Create User", () => {
  it(" Save and Create User ", (done) => {
    const addUser = new User({
      name: "Kianoush",
      family: "Dortaj",
    });
    addUser
      .save()
      .then(() => {
        assert(!addUser.isNew);
        done();
      });
  });
});

当我运行测试时,使用是在数据库中创建的,但它显示了这个错误并且测试失败:

错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用“done()”;如果返回 Promise,请确保它已解决。 (F:\Projects\Nodejs\MongooDB\test\create-user_test.js) 在 listOnTimeout (internal/timers.js:549:17) 在 processTimers (internal/timers.js:492:7)

有什么问题吗?我该如何解决??

【问题讨论】:

标签: javascript node.js mocha.js


【解决方案1】:

这里有几个解决方案可以检查。

"scripts": {
          "test": "mocha --timeout 10000"  <= increase this from 1000 to 10000
           },

#### OR ###

it("Test Post Request", function(done) {
     this.timeout(10000);  //add timeout.
});

也可以应用特定于测试的超时,或者使用this.timeout(0) 一起禁用超时:

it('should take less than 500ms', function(done){
  this.timeout(500);
  setTimeout(done, 300);
});

如果两者都不起作用。试试这个

const delay = require('delay')

describe('Test', function() {
    it('should resolve', async function() {
      await delay(1000)
    })
})

异步函数中 done 参数的存在会以某种方式中断测试,即使它没有被使用,即使在测试结束时调用了 done()。

【讨论】:

  • 值得注意的是,您需要为匿名谓词使用 function() 形式才能使其工作。胖箭头形式“async () => {”专门在封闭上下文中运行,因此没有“this”对象。如果你犯了这个错误,你可能会看到类似“TypeError: this.timeout is not a function”。
猜你喜欢
  • 2019-07-24
  • 2017-09-13
  • 2019-06-24
  • 2018-07-02
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 2018-06-07
相关资源
最近更新 更多