Typescript and Jest: Avoiding type errors on mocked functions
When wanting to mock external modules with Jest, we can use the jest.mock() method to auto-mock functions on a module.
We can then manipulate and interrogate the mocked functions on our mocked module as we wish.
For example, consider the following contrived example for mocking the axios module:
import myModuleThatCallsAxios from '../myModule';
import axios from 'axios';
jest.mock('axios');
it('Calls the GET method as expected', async () => {
const expectedResult: string = 'result';
axios.get.mockReturnValueOnce({ data: expectedResult });
const result = await myModuleThatCallsAxios.makeGetRequest();
expect(axios.get).toHaveBeenCalled();
expect(result).toBe(expectedResult);
});
The above will run fine in Jest but will throw a Typescript error:
Property 'mockReturnValueOnce' does not exist on type '(url:
string, config?: AxiosRequestConfig | undefined) => AxiosPromise'.
The typedef for axios.get rightly doesn't include a mockReturnValueOnce property. We can force Typescript to treat axios.get as an Object literal by wrapping it as Object(axios.get), but:
What is the idiomatic way to mock functions while maintaining type safety?Please use the mocked function from ts-jest The mocked test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source. It makes use of the latest TypeScript feature, so you even have argument types completion in the IDE (as opposed to jest.MockInstance). import myModuleThatCallsAxios from '../myModule'; import axios from 'axios'; import { mocked } from 'ts-jest/utils' jest.mock('axios'); // OPTION - 1 const mockedAxios = mocked(axios, true) // your original `it` block it('Calls the GET method as expected', async () => { const expectedResult: string = 'result'; mockedAxios.mockReturnValueOnce({ data: expectedResult }); const result = await myModuleThatCallsAxios.makeGetRequest(); expect(mockedAxios.get).toHaveBeenCalled(); expect(result).toBe(expectedResult); }); // OPTION - 2 // wrap axios in mocked at the place you use it('Calls the GET method as expected', async () => { const expectedResult: string = 'result'; mocked(axios).get.mockReturnValueOnce({ data: expectedResult }); const result = await myModuleThatCallsAxios.makeGetRequest(); // notice how axios is wrapped in `mocked` call expect(mocked(axios).get).toHaveBeenCalled(); expect(result).toBe(expectedResult); }); I can't emphasise how great mocked is, no more type-casting ever.
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/75bce83af615d4f9b85d04bb44a4a7d110eb7c052c3eb4beec69b2fb27056bb9