I'm trying to mock a TypeScript class with Jest and I'm obviously doing something because receive the following error:
error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.
This is my code:
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
}),
}))
})
})
The full error:
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>(() => ({
~~~
UPDATE
If it is of any relevance, this is my Jest config:
module.exports = {
moduleFileExtensions: ['ts', 'js'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
testMatch: ['**/src/**/*.test.(ts)'],
testEnvironment: 'node',
};
Jest has the following signature for jest.fn:
/**
* Creates a mock function. Optionally takes a mock implementation.
*/
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;
So you need to specify the array of types for the args, in your particular case you could just pass an empty array as there are no args in your implementation function.
const MockFoo = jest.fn<Foo, []>(() => ({
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With