![](/img/trans.png)
[英]Code coverage concern on promise/asynchronous unit testing using nockjs and jest
[英]Asynchronous Javascript code testing using Jest works when it is not supposed to
Jest的文档提供了一个负面示例,说明了在测试异步代码时不应该做什么。 我是这样实现的:
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函数中的第一个之前触发。
此外,当我的超时设置为1500ms时,测试在0.866s内失败。 如果根本不应该调用我的回调,Jest怎么会收到错误的回调数据(花生酱2)?
因为您的测试看起来应该是async
,但实际上由于代码错误而实际上是synchronous
。
你有以下内容,看起来像它的设计要调用的方法cb
后1500ms
, 但是你打电话cb
立刻 :
setTimeout(cb('peanut butter2'), 1500);
依次将string
传递到您的callback
函数中,该函数立即/同步运行expect
。
您可能想要的是这样的:
setTimeout(function() { cb('peanut butter2') }, 1500);
或者,让setTimeout
将arg传递给您的cb
函数并调用它:
setTimeout(cb, 1500, 'peanut butter2')
实际会在1500ms
之后调用cb
函数,这与预期的一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.