【发布时间】:2019-02-06 21:16:41
【问题描述】:
是否可以用 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);
});
});
我尝试了多种方式来创建一个模拟对象来满足这一点,但都没有奏效。例如给它分配这个模拟:
let multiplierMock = jest.fn(() => ({ multiply: jest.fn() }));
会产生以下内容:
Error - Type 'Mock<{ multiply: Mock<{}>; }>' is not assignable to type 'IMultiplier'.
【问题讨论】:
-
如何在
Math的实例中创建/分配multiplier? -
@brian-lives-outdoors 这显然是一个人为的例子,但是在代码库中,multiplier 会被传递到 Math 的构造函数中,并且之后会分配给 multiplier 属性的实例(例如以上测试)。
标签: typescript mocking jestjs