我正在尝试使用 Jest 模拟 TypeScript 类,我显然正在做某事,因为收到以下错误:
error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.
这是我的代码:
Foo.ts
export default class Foo {
bar(): number {
return Math.random()
}
}
Foo.test.ts
import Foo from './Foo'
describe('Foo', () => {
it("should pass", () => {
const MockFoo = jest.fn<Foo>(() => ({
bar: jest.fn(() => {
return 123
}),
}))
})
})
完整的错误:
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/Foo.test.ts:6:29 - error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.
6 const MockFoo = jest.fn<Foo>(() => ({
~~~
更新
如果有任何相关性,这是我的 Jest 配置:
module.exports = {
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
testMatch: ['**/src/**/*.test.(ts)'],
testEnvironment: 'node',
};
最佳答案
Jest 具有以下 jest.fn 的签名:
/**
* Creates a mock function. Optionally takes a mock implementation.
*/
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;
因此,您需要为 args 指定类型数组,在您的特定情况下,您可以只传递一个空数组,因为您的实现函数中没有 args。
const MockFoo = jest.fn<Foo, []>(() => ({
关于typescript - 开 Jest mock TypeScript 类 "No overload expects 1 type arguments",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941165/