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
You can use the ts-jest's mocked() function:
This is all type safe and compiles without warnings in TypeScript:
import Foo from './Foo'
import {mocked} from 'ts-jest/utils'
function argIsFoo(foo : Foo) {
; // do nothing
}
describe('Foo', () => {
it("should pass", () => {
const mockFoo = mocked({
bar: jest.fn(() => {
return 123
})
});
// mockFoo is compatible with Foo class
argIsFoo(mockFoo);
// method has the right type
expect(mockFoo.bar()).toEqual(123);
// can use the mock in expectations
expect(mockFoo.bar).toHaveBeenCalled();
// is type safe access method as a mock
expect(mockFoo.bar.mock.calls.length).toEqual(1);
});
});
If you only want to mock out some of Foo's methods, then in mocked() you need to cast your mock object with as unknown as Foo:
import {mocked} from 'ts-jest/utils'
class Foo {
bar(): number {
return Math.random();
}
dontMockMe(): string {
return "buzz";
}
}
function argIsFoo(foo : Foo) {
; // do nothing
}
describe('Foo', () => {
it("should pass", () => {
const mockFoo = mocked({
bar: jest.fn(() => {
return 123
})
} as unknown as Foo);
// mockFoo is compatible with Foo class
argIsFoo(mockFoo);
// method has the right type
expect(mockFoo.bar()).toEqual(123);
// can use the mock in expectations
expect(mockFoo.bar).toHaveBeenCalled();
// is type safe access method as a mock
expect(mockFoo.bar.mock.calls.length).toEqual(1);
});
});