javascript - 如果模拟了两种方法,则 Jest 测试失败
问题描述
我在测试中遇到了令人困惑的情况。请参阅下面的代码。
文件.js
class Test {
constructor() {}
async main() {
const a = await this.aux1("name1");
const b = await this.aux2("name2");
}
async aux1(name) {
console.log(name)
}
async aux2(name) {
console.log(name)
}
}
module.exports = Test;
文件.spec.js
describe('Concept proof', () => {
const module = require("./file.js");
const inst = new module();
test('should call aux1', async () => {
const a = jest.fn(() => "return");
inst.aux1 = a
inst.main()
expect(a).toHaveBeenCalled()
});
test('should call aux2', async () => {
const b = jest.fn(() => "return");
inst.aux2 = b
inst.main()
expect(b).toHaveBeenCalled()
});
});
结果
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
18 | inst.main()
19 |
> 20 | expect(b).toHaveBeenCalled()
| ^
21 | });
22 | });
at Object.<anonymous> (file.spec.js:20:19)
如果从 main 调用 aux1,则不会调用方法 aux2,但如果我从 main 中删除 aux1 调用,则会按预期运行。
我无法在文档中找到该行为的解释。我误解了一些东西,或者即使之前调用了 aux1,也应该调用正常的行为 aux2?任何帮助将不胜感激!
任何帮助将不胜感激!
解决方案
你应该使用await inst.main();
.
inst.main()
是一种异步方法。如果await
不使用,主线程会继续执行,不会等待inst.main()
.
这意味着该expect(b).toHaveBeenCalled()
语句将在inst.main()
方法之前执行。
推荐阅读
- javascript - 推入 forEach 不适用于异步功能
- android - 当应用程序在后台/内存中时,Android如何将数据(文本/ URL)发送到颤动的应用程序?
- python - Cython:扩展类型的链接列表
- javascript - 来自验证的 Javascript 点击事件
- jquery - 在按钮单击时循环遍历元素,然后全部隐藏,然后使用 jQuery 再次开始循环
- python - 在 Django 模型中删除新列或删除现有表时如何保留以前的数据?
- kotlin - 如何修复所需的 Long 发现 Long?
- unit-testing - Rust 单元测试 - 函数调用在最后挂起并且不返回
- apache-storm - Apache Storm 元组在 10 分钟后超时,但 topology.message.timeout.secs 配置为 5 分钟
- python - Tkinter 被线程冻结