如何為正在模擬的類模擬實體方法jest.mock?
例如,模擬一個類Logger:
import Person from "./Person";
import Logger from "./Logger";
jest.mock("./Logger");
describe("Person", () => {
it("calls Logger.method1() on instantiation", () => {
Logger.method1.mockImplementation(() => {}) // This fails as `method1` is an instance method but how can the instance method be mocked here?
new Person();
expect(Logger.method1).toHaveBeenCalled();
});
});
uj5u.com熱心網友回復:
在Logger模擬類時,您可以提供一個模塊工廠作為jest.mock. 您可以參考檔案以獲取更多資訊。
import Person from "./Person";
const mockConstructor = jest.fn();
const mockMethod1 = jest.fn();
jest.mock("./Logger.js", () => ({
default: class mockLogger {
constructor() {
mockConstructor();
}
method1() {
mockMethod1();
}
},
__esModule: true
}));
it("works", () => {
const p = new Person();
expect(mockConstructor).toHaveBeenCalled();
p.method1();
expect(mockMethod1).toHaveBeenCalled();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/476625.html
標籤:javascript 单元测试 开玩笑的 嘲弄
