Javascript 开玩笑预期已调用模拟函数,但未调用该函数
假设我有MyFile.jsJavascript 开玩笑预期已调用模拟函数,但未调用该函数,javascript,mocking,jestjs,Javascript,Mocking,Jestjs,假设我有MyFile.js export const test2 = () => {} export const test = () => { test2(); } 然后我有了MyFile.test.js: import * as MyFile from "./MyFile"; it("when test() is called should call test2", () => { const spy = jest.spyOn(MyFile, "test2");
export const test2 = () => {}
export const test = () => {
test2();
}
然后我有了MyFile.test.js:
import * as MyFile from "./MyFile";
it("when test() is called should call test2", () => {
const spy = jest.spyOn(MyFile, "test2");
MyFile.test();
expect(spy).toHaveBeenCalled();
})
为什么调用了错误预期的模拟函数,但在这种情况下没有调用它?
将对象的属性包装在spy中
MyFile
表示从MyFile.js
sojest.spyOn(MyFile,“test2”)导出的模块代码>将test2
的模块导出包装在间谍文件中
…但是当调用MyFile.test
时,它会直接调用test2
,因此间谍永远不会被调用
修复它的一种方法是将test2
移动到它自己的模块中:
MyFile.js
export const test2 = () => {}
export const test = () => {
test2();
}
import { test2 } from './OtherModule';
export const test = () => {
test2();
}
import * as MyFile from './MyFile'; // <= import module bindings
export const test2 = () => {}
export const test = () => {
MyFile.test2(); // <= call the module export for test2
}
OtherModule.js
export const test2 = () => {}
MyFile.test.js
import * as MyFile from "./MyFile";
import * as OtherModule from "./OtherModule";
it("when test() is called should call test2", () => {
const spy = jest.spyOn(OtherModule, "test2");
MyFile.test();
expect(spy).toHaveBeenCalled(); // Success!
})
import * as MyFile from "./MyFile";
it("when test() is called should call test2", () => {
const spy = jest.spyOn(MyFile, "test2");
MyFile.test();
expect(spy).toHaveBeenCalled(); // Success!
})
另一种方法是导入模块绑定,这样您就可以为test2
调用模块导出:
MyFile.js
export const test2 = () => {}
export const test = () => {
test2();
}
import { test2 } from './OtherModule';
export const test = () => {
test2();
}
import * as MyFile from './MyFile'; // <= import module bindings
export const test2 = () => {}
export const test = () => {
MyFile.test2(); // <= call the module export for test2
}