Допустим, у меня есть 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");
MyFile.test();
expect(spy).toHaveBeenCalled();
})
Почему я получаю ошибку Expected mock function to have been called, but it was not called
для этого случая?
jest.spyOn
оборачивает свойство объекта в шпион.
MyFile
представляет модуль, экспортируемый из MyFile.js
, поэтому jest.spyOn(MyFile, "test2");
оборачивает экспорт модуля для test2
в шпион...
... но когда MyFile.test
звонят, он звонит test2
напрямую, так что шпиону никогда не звонят.
Один из способов исправить это — переместить test2
в отдельный модуль:
MyFile.js
import { test2 } from './OtherModule';
export const test = () => {
test2();
}
OtherModule.js
export const test2 = () => {}
Мой файл.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!
})
Другой способ — импортировать привязки модуля, чтобы вы могли вызвать экспорт модуля для test2
:
MyFile.js
import * as MyFile from './MyFile'; // <= import module bindings
export const test2 = () => {}
export const test = () => {
MyFile.test2(); // <= call the module export for test2
}
Мой файл.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(); // Success!
})