我尝试了多种方法,以开玩笑的方式模拟通用函数,但均未成功。在我看来,这是正确的方法:
interface ServiceInterface {
get<T>(): T;
}
class Service implements ServiceInterface {
get = jest.fn(<T>(): T => null);
}
在编译时会引发以下错误:
error TS2416: Property 'get' in type 'Service' is not assignable to the same property in base type 'ServiceInterface'.
Type 'Mock<{}, any[]>' is not assignable to type '<T>() => T'.
Type '{}' is not assignable to type 'T'.
您能告诉我正确的方法吗?
谢谢
答案 0 :(得分:0)
我使用sinon进行模拟,可以使用以下方式安装:
npm i sinon --save-dev
然后在其中一个测试中进行模拟,您可以执行以下操作:
const mock = sinon.mock(service); // you want the value passed in to mock to be the actualy object being mocked
mock.expects('get').returns(null) // this would expect get to be called once and the return value is null
mock.restore(); // restores all mocked methods
mock.verify(); // verifies the expectations
答案 1 :(得分:0)
我认为,如果您创建一个接口,那么就让它成为通用接口,而不是为每个属性设置通用接口。
interface ServiceInterface<T> {
get(): T;
}
使用Jest创建模拟对象时:
class Service<T> implements ServiceInterface<T> {
get = jest.fn<T, []>((): T => null);
}
const instance = new Service<string>();
const result = instance.get(); // typeof result === "string"
对于您的情况,您需要模拟的是返回值get()
interface ServiceInterface {
get<T>(): T;
}
const mockedGet = jest.fn();
class Service implements ServiceInterface {
get<T>(): T {
return mockedGet();
}
}
const instance = new Service();
mockedGet.mockReturnValue("Hello!");
const result = instance.get<string>(); // now, result is a string