这是一个用 Jest (v20.0.4) 编写的测试套件。
前 3 个测试是预期行为,我的问题与 Test4 有关。
test('Test1: the list should contain 7', () => {
const data = [1, 2, 7, 9];
expect(data).toContain(7);
});
// > Passes as expected
test('Test2: the list should contain 7', () => {
const data = [1, 2, 7, 9];
expect(data).toContain(8);
});
// > Fails as expected; Expected array: [1, 2, 7, 9] To contain value: 8
test('Test3: the list should contain 7', (done) => {
function callback(data) {
expect(data).toContain(7);
done();
}
setTimeout(() => {
callback([1, 2, 7, 9]);
}, 500);
});
// > Passes as expected
test('Test4: the list should contain 7', (done) => {
function callback(data) {
expect(data).toContain(8);
done();
}
setTimeout(() => {
callback([1, 2, 7, 9]);
}, 500);
});
// > Fails with Error "Timeout - Async callback was not invoked within timeout specified"
这是我的问题:在 Test4 中,
done()
在 expect
之后立即调用陈述。所以,即使期望语句没有通过,我猜它应该会失败并出现类似于 Test2:
(Expected array: [1, 2, 7, 9] To contain value: 8)
的错误。但是,它失败并出现如上所示的超时错误,这表明
done()
永远不会被调用。为什么?我不明白!
有人可以指导我完成这种行为吗?
我扫描了docs但找不到与此相关的任何内容。
最佳答案
在您的代码中,expect
调用 throws 和 done
永远达不到。因此,Jest 会一直等到超时并发出您注意到的令人讨厌的、不清楚的错误。
解决方案是捕获抛出并调用 done(error)
向 Jest 运行者表明测试失败。
test('Test4: the list should contain 7', done => {
function callback(data) {
try {
expect(data).toContain(8);
done();
}
catch (err) {
done(err);
}
}
setTimeout(() => {
callback([1, 2, 7, 9]);
}, 500);
});
运行此操作会产生所需的结果:Error: expect(received).toContain(expected) // indexOf
Expected value: 8
Received array: [1, 2, 7, 9]
来自 docs :If the
expect
statement fails, it throws an error anddone()
is not called. If we want to see in the test log why it failed, we have to wrapexpect
in atry
block and pass the error in thecatch
block todone
. Otherwise, we end up with an opaque timeout error that doesn't show what value was received byexpect(data)
.
关于javascript - 在 Jest : done() not being called as expected 中测试异步代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603954/