Javascript 如果模拟了两个方法,Jest测试将失败
我在考试中遇到了一个令人困惑的情况。请参阅下面的代码 file.js file.spec.js 结果Javascript 如果模拟了两个方法,Jest测试将失败,javascript,testing,jestjs,mocking,Javascript,Testing,Jestjs,Mocking,我在考试中遇到了一个令人困惑的情况。请参阅下面的代码 file.js file.spec.js 结果 expect(jest.fn()).tohavebeencall() 预期呼叫数:>=1 收到的呼叫数:0 18 |主仪表() 19 | >20 |期望(b).被调用() | ^ 21 | }); 22 | }); 反对。(file.spec.js:20:19) 如果从main调用aux1,则不会调用aux2方法,但如果从main删除aux1调用,则
expect(jest.fn()).tohavebeencall()
预期呼叫数:>=1
收到的呼叫数:0
18 |主仪表()
19 |
>20 |期望(b).被调用()
| ^
21 | });
22 | });
反对。(file.spec.js:20:19)
如果从main调用aux1,则不会调用aux2方法,但如果从main删除aux1调用,则其行为与预期相同
我在文件上找不到这种行为的解释。我误解了什么,或者正常的行为应该是调用aux2,即使之前调用了aux1?
任何帮助都将不胜感激
任何帮助都将不胜感激 您应该使用
wait inst.main()代码>
inst.main()
是一种异步方法。如果未使用wait
,则主线程将继续执行,而不会等待inst.main()
的完成
这意味着expect(b).toHaveBeenCalled()
语句将在inst.main()
方法之前执行。为什么要修补要测试的部分内容?还要注意的是,您的测试泄漏状态-inst
只创建了一次,因此随着时间的推移,它的更多方法会被mock所取代。我找不到任何理由带来超出需要的代码。我现在觉得自己太愚蠢了。非常感谢。
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;
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)