Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mocking TypeScript class "No overload expects 1 type arguments"

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',
};
like image 964
Luke Avatar asked Oct 19 '25 02:10

Luke


1 Answers

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, []>(() => ({
like image 100
Chesley Avatar answered Oct 22 '25 04:10

Chesley