替代使用 jest.setTimeout
Alternative to using jest.setTimeout
目前我的 NodeJS/Express/MongoDB 应用程序中配置了一些测试(Jest + Supertest)。
根据我的经验,当服务器实际与 MongoDB 成功连接(可能需要几秒钟)时可能会有很大差异。
我的测试失败了,因为它在 5000 毫秒后超时(我相信这是 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
目前我的 NodeJS/Express/MongoDB 应用程序中配置了一些测试(Jest + Supertest)。 根据我的经验,当服务器实际与 MongoDB 成功连接(可能需要几秒钟)时可能会有很大差异。
我的测试失败了,因为它在 5000 毫秒后超时(我相信这是 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