我正在使用 mocha 运行测试
it('should allow a POST to /users', async function () {
const res = await request.post('/users').send(firstUserBody);
expect(res.status).to.equal(201);
expect(res.body).not.to.be.empty;
expect(res.body).to.be.an('object');
expect(res.body.id).to.be.a('string');
firstUserIdTest = res.body.id;
});
但是我有一个错误
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
如果我使用 done() 执行此操作,则该函数不是异步的,但它应该是
it('should allow a POST to /users', async function (done) {
const res = await request.post('/users').send(firstUserBody);
expect(res.status).to.equal(201);
expect(res.body).not.to.be.empty;
expect(res.body).to.be.an('object');
expect(res.body.id).to.be.a('string');
firstUserIdTest = res.body.id;
done();
});
我该怎么办?
最佳答案
Mocha有两种设置超时的方法:
(我会在测试 API 调用时使用最少 20 秒)
在测试或描述 block 中
describe('a suite of tests', function() { this.timeout(20000); ...
(注意不要使用箭头函数,因为那样会导致
this.
不起作用)配置级别 -
.mocharc.js
运行时文件或标志--timeout 20000
甚至使用 API (mocha.setup( )
).我更喜欢使用
.mocharc.js.
,您可以在其中放置如下内容:module.exports = { bail: true, timeout: 5 * 60 * 1000, // 5 minute timeout spec: ['specs/'] };
文档和示例:
https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js
https://mochajs.org/#configuring-mocha-nodejs
https://mochajs.org/#-timeout-ms-t-ms
PS 你不应该需要带有异步函数的done()
关于node.js - 我应该为错误做些什么对于异步测试和 Hook ,确保调用 "done()";如果返回一个 Promise,确保它 resolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68079009/