Typescript 类中的类和函数的Jest模拟类实例
我有一个正在测试的类,我们称它为ToTest.ts,它实例化了另一个类的实例unrelated.ts,并调用了一个名为doSomething的方法Typescript 类中的类和函数的Jest模拟类实例,typescript,testing,mocking,jestjs,Typescript,Testing,Mocking,Jestjs,我有一个正在测试的类,我们称它为ToTest.ts,它实例化了另一个类的实例unrelated.ts,并调用了一个名为doSomething的方法 // ToTest.ts const irrelevant = new Irrelevant(); export default class ToTest { // ... some implementation, constructor, etc. public static callIrrelevant() { return
// ToTest.ts
const irrelevant = new Irrelevant();
export default class ToTest {
// ... some implementation, constructor, etc.
public static callIrrelevant() {
return irrelevant.doSomething();
}
}
//Irrelevant.ts
export default class Irrelevant {
// ... some implementation, constructor, etc.
public doSomething() {
console.log("doing something");
}
}
如何在我的jest测试中模拟无关的.doSomething()
我试过:
import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
Irrelevant.prototype.doSomething = () => jest.fn().mockImplementation(() => {
console.log(`function got called`)
});
const toTest = new ToTest();
toTest.callIrrelevant();
});
test('irrelevant.doSomething is mocked -- second try' => {
jest.mock('../some/path/irrelevant')
const mockDoSomething = jest.spyOn(Irrelevant, "doSomething"); // Gives error: Argument of type '"doSomething"' is not assignable to parameter of type 'never'.
findMock.mockImplementation(() => {
console.log(`function got called`)
});
const toTest = new ToTest();
toTest.callIrrelevant();
});
});
这两个测试都不会触发模拟实现。我怎样才能正确地模拟这个问题?< P>你必须把McCK实现看作是<代码>的构造函数无关的< /代码>。它将返回什么将是你的嘲笑。所以你可以这样做:
import Irrelevant from '../some/path/irrelevant';
jest.mock('../some/path/irrelevant')
const spyDoSomething = jest.fn();
(Irrelevant as any).mockImplementation(() => {
return { doSomething: spyDoSomething };
})
属性“mockImplementation”不存在于类型“typeof Unrelated”上。
我更新了答案。我只是对any进行了不相关的强制转换,因为它无论如何都会被模拟。您可以使用ts jest
中的mocked()
方法:参见
import Irrelevant from '../some/path/irrelevant';
test('irrelevant.doSomething is mocked' => {
Irrelevant.prototype.doSomething = () => jest.fn(() => {
console.log(`function got called`)
});
const toTest = new ToTest();
toTest.callIrrelevant();
});