如何解决替代使用jest.setTimeout
目前,我已经在NodeJS / Express / MongoDB应用中配置了一些测试(Jest + Supertest)。 根据我的经验,当服务器实际上成功连接到MongoDB时(可能要花几秒钟),情况可能会大不相同。
我的测试失败了,因为它在5000ms之后超时(我相信这是Jests的默认超时)。
我能够通过在测试的第一部分中定义一个jest.setTimeout(15000)
来绕过这个问题,它们看起来都像这样:
test('POST' + endpointUrl,async () => {
jest.setTimeout(15000);
const response = await request(app)
.post(endpointUrl)
.send(newTodo);
ASSERTIONS
});
我想知道这是否是解决我的问题的正确方法。
解决方法
如果您具有异步功能并且必须等待响应,只需使用done
关键字作为测试回调参数即可。
test('POST' + endpointUrl,async (done) => {
const response = await request(app)
.post(endpointUrl)
.send(newTodo);
ASSERTIONS
done();
});
或者:
test('POST' + endpointUrl,done => {
request(app)
.post(endpointUrl)
.send(newTodo)
.then(res => {
ASSERTIONS
done();
})
.catch(error => {
fail(`It must be done,but catched because of: ${error}`);
})
});
有关更多信息,只需检查以下主题:Testing Asynchronous Code
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。