我使用jest.fn()函数测试节点restapi服务器。我大量使用async / await并遇到了一个我简化为的问题:
test1.js
const test1 = async (res) => {
res.status(500).send(); // Works here
// Use a timer as an example, but should work with any promises
await new Promise(resolve => setTimeout(resolve, 500));
res.status(500).send(); // Doesn't work here
}
module.exports = test1;
test1.test.js
const jest = jest;
import test1 from './test1';
const res01 = {};
let status;
let send;
beforeEach(() => {
status = jest.fn();
send = jest.fn();
status.mockReturnValue({
send
});
res01.status = status;
});
test('just testing ...', () => {
test1(res01);
expect(status).toHaveBeenCalledWith(500);
expect(send).toHaveBeenCalledTimes(1);
});
玩笑设置
"jest": {
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest"
},
"globals": {
"NODE_ENV": "test"
},
"moduleFileExtensions": [
"js"
],
"moduleDirectories": [
"node_modules"
],
"moduleNameMapper": {
"\\.(less|css|jpg|png)$": "<rootDir>/src/test/empty-module.js"
}
},
如果将res.status(500).send()放置在第一次使用await之前,则测试成功,而将其放置在测试失败之后。状态不被调用。为什么?
答案 0 :(得分:2)
在测试中,您必须await
async
方法。
ref:https://facebook.github.io/jest/docs/en/tutorial-async.html#async-await