例如,我有这样的基本内容:
it.only('tests something', (done) => {
const result = store.dispatch(fetchSomething());
result.then((data) => {
const shouldBe = 'hello';
const current = store.something;
expect(current).to.equal(shouldBe);
done();
}
});
当 current
与 shouldBe
不匹配时,我收到的是通用超时消息,而不是一条消息说它们不匹配:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
就好像期望暂停脚本什么的。我该如何解决?这使得调试几乎不可能。
最佳答案
期望不是暂停脚本,而是在您点击完成回调之前抛出异常,但由于它不再位于测试方法的上下文中,因此也不会被测试套件拾取,因此您永远无法完成测试。然后你的测试就会一直旋转,直到达到超时为止。
您需要在回调或 Promise
的错误处理程序中的某个时刻捕获异常。
it.only('tests something', (done) => {
const result = store.dispatch(fetchSomething());
result.then((data) => {
const shouldBe = 'hello';
const current = store.getState().get('something');
try {
expect(current).to.equal(shouldBe);
done();
} catch (e) {
done(e);
}
});
});
或
it.only('tests something', (done) => {
const result = store.dispatch(fetchSomething());
result.then((data) => {
const shouldBe = 'hello';
const current = store.getState().get('something');
expect(current).to.equal(shouldBe);
})
.catch(done);
});
编辑
如果您不反对引入另一个库,那么有一个相当不错的库调用 chai-as-promised 。这为您提供了一些用于此类测试的不错的实用程序。
关于javascript - 使用 Mocha/Chai 测试异步函数时,无法满足期望总是会导致超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748343/