可以用jest模拟typescript接口吗?
例如:
import { IMultiplier } from "./IMultiplier";
export class Math {
multiplier: IMultiplier;
public multiply (a: number, b: number) {
return this.multiplier.multiply(a, b);
}
}
然后在测试中:
import { Math } from "../src/Math";
import { IMultiplier } from "../src/IMultiplier";
describe("Math", () => {
it("can multiply", () => {
let mathlib = new Math();
mathlib.multiplier = // <--- assign this property a mock
let result = mathlib.multiply(10, 2);
expect(result).toEqual(20);
});
});
我已经try 过创建一个模拟对象来满足这一要求,但没有一种方法有效.例如,将其分配给此模拟:
let multiplierMock = jest.fn(() => ({ multiply: jest.fn() }));
将产生以下内容:
Error - Type 'Mock<{ multiply: Mock<{}>; }>' is not assignable to type 'IMultiplier'.