当使用Mocha/Chai测试异步函数时,与期望值不匹配总是会导致超时
When testing async functions with Mocha/Chai, a failure to match an expectation always results in a timeout
例如,我有一些基本的东西,比如:
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
不匹配时,我得到的不是说它们不匹配的消息,而是一般的超时消息:
错误:超过了2000ms的超时时间。确保done()回调正在在该测试中调用。
这就好像期望是暂停脚本或其他什么。我该如何解决这个问题?这使得调试几乎不可能。
期望的不是暂停脚本,而是在您调用done
回调之前抛出异常,但由于它不再在测试方法的上下文中,它也不会被测试套件接收,因此您永远不会完成测试。然后你的测试只是旋转,直到达到超时。
您需要在某个时刻捕获异常,无论是在回调中还是在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);
});
编辑
如果你不反对引进另一个图书馆,有一个相当不错的图书馆叫柴。这为这种测试提供了一些不错的实用程序。
相关文章:
- 高库存时期时间与时区不匹配
- react路由器使用简单的javascript路由器配置来处理不匹配的路径
- Javascript:图像与单选按钮的值不匹配
- 文本区域(jQuery)的结果不匹配
- 如果状态不匹配,则缩小为丑陋
- 为什么我网页的facebook点赞数与该网页的facebook页面不匹配
- 使用jscodeshift添加表达式时,错误{..}与类型字符串不匹配
- JavaScript正则表达式不匹配
- row.entity.xxxx属性doensn'排序后不匹配
- Url.Content中的Url不匹配
- 控件坐标与组坐标不匹配
- 使用正则表达式查找字符串中的不匹配字符
- CSS Media Query 和 Javascript/jQuery 不匹配
- 始终在 jQuery 自动完成中显示特定选项,即使它与输入不匹配
- 如果项目不匹配,则显示变量
- 正则表达式匹配 JQM 路由器插件中的“项目”但不匹配“项目”
- Lodash 从与值数组不匹配的数组中获取项目
- 比较 2 个数组并得到这些变量不匹配
- jquery DataTable 数据格式和警告 - 添加的数据与已知列数不匹配
- 当使用Mocha/Chai测试异步函数时,与期望值不匹配总是会导致超时