【发布时间】:2019-07-07 21:12:18
【问题描述】:
我需要使用 jest v24+ 创建我的打字稿类的模拟实现。我特别想创建一个模拟类,该类被注入到构造函数中并模拟将被调用以返回特定响应的函数。
如何为每个测试创建一个模拟?
更多信息:
我已经开始了一个新项目,现在正在使用 jest v24,它在编写测试时产生了一个我无法解决的问题。
在 jest v23 中使用下面的示例,以前我可以模拟 Randomiser 类,如下所示:
const Mock = jest.fn<Randomiser>(() => ({
getRandom: jest.fn().mockReturnValue(10)
}));
这将成功编译和构建。
从 v24 开始,fn 函数采用并添加通用 <T, Y extends any[]> 我不知道这是否与行为改变有关,但现在我收到一个错误:
类型 '{ getRandom: Mock; 中缺少属性 'rand' }' 但在 'Randomiser'.ts(2741) 类型中是必需的
import "jest";
class Randomiser {
public getRandom(): number {
return this.rand();
}
private rand(): number {
return Math.random();
}
}
class Multiplier {
private randomiser: Randomiser;
constructor(randomiser: Randomiser) {
this.randomiser = randomiser;
}
multiplyRandom(factor: number): number {
return Math.floor(this.randomiser.getRandom() * factor);
}
}
describe("tests", () => {
it("10 x 2 = 20", () => {
const Mock = jest.fn<Randomiser, any>(() => ({
getRandom: jest.fn().mockReturnValue(10),
rand: jest.fn() //with this line I get an error because it should be private, without this line I get the error above.
}));
expect(new Multiplier(new Mock()).multiplyRandom(2)).toBe(20);
})
})
我希望能够像使用 v23 一样编写我的模拟,即我可以模拟类并且只需要模拟我要调用的函数。
现在我必须模拟所有函数,包括它抱怨的私有函数和私有属性不是私有的。
【问题讨论】:
标签: typescript visual-studio-code jestjs