用玩笑来模拟泛型函数

Max*_*Max 10 typescript jestjs ts-jest

我尝试了很多方法来用玩笑来模拟通用函数,但没有成功。这是我认为正确的方法:

interface ServiceInterface {
    get<T>(): T;
}

class Service implements ServiceInterface {
    get = jest.fn(<T>(): T => {
        throw new Error("Method not implemented.");
    });
}
Run Code Online (Sandbox Code Playgroud)

编译时会抛出以下错误:

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'.
Run Code Online (Sandbox Code Playgroud)

你能告诉我正确的方法吗?

谢谢

Der*_*uah -4

我使用sinon进行模拟,可以使用以下命令安装:

npm i sinon --save-dev
Run Code Online (Sandbox Code Playgroud)

然后,要在其中一个测试中进行模拟,您可以执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)