【发布时间】:2018-08-06 00:42:11
【问题描述】:
Jest 的docs 提供了一个反例,说明在测试异步代码时不应该做什么。我是这样实现的:
const expect = require('expect');
function fetchData(cb) {
setTimeout(cb('peanut butter2'), 1500);
}
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
我跑了npx jest test.js,这是输出:
Fabians-MacBook-Pro:playground fabian$ npx jest test.js
FAIL ./test.js
✕ the data is peanut butter (6ms)
● the data is peanut butter
expect(received).toBe(expected)
Expected value to be (using Object.is):
"peanut butter"
Received:
"peanut butter2"
at callback (playground/test.js:9:22)
at fetchData (playground/test.js:4:16)
at Object.<anonymous>.test (playground/test.js:12:5)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.866s, estimated 1s
Ran all test suites matching /test.js/i.
我不明白结果。
为什么即使我没有调用 done(),它仍然可以工作,因为 Jest 建议您这样做来测试异步代码?我很确定 setTimeout 是异步的,因为我在一个空白测试脚本中使用 console.log() 语句对其进行了测试,第二个在第一个包含在 setTimeout 函数中之前触发。
此外,当我的超时设置为 1500 毫秒时,测试在 0.866 秒内失败。当我的回调甚至不应该被调用时,Jest 怎么会收到错误的回调数据(花生酱2)?
【问题讨论】:
标签: javascript asynchronous testing jestjs