jest typescript property mock does not exist on type
For anyone getting here, a bit better than casting to any
might be casting as jest.Mock
const callback = (foo.addListener as jest.Mock).mock.calls[0][0];
Update Sep 2021
To get a mocked function that both fulfills the mocked function type and the jest mock type jest.MockedFunction
can be used:
const addListenerMock = addListener as jest.MockedFunction<typeof addListener>;
You can use jest.spyOn
in combination with functions like mockImplementation
to mock a function while preserving type safety in TypeScript:
class Foo { addListener = (callback: () => number) => { } func = () => { this.addListener(() => 1); }}test('working', () => { const foo = new Foo(); const mockAddListener = jest.spyOn(foo, 'addListener'); // spy on foo.addListener mockAddListener.mockImplementation(() => { }); // replace the implementation if desired foo.func(); // will call addListener with a callback const callback = mockAddListener.mock.calls[0][0]; expect(callback()).toEqual(1); // SUCCESS});
Got the error below when using axios
.
TS2339 (TS) Property 'mockResolvedValueOnce' does not exist on type'AxiosStatic'
Tried using axios as jest.Mock
but got the error below:
TS2352 (TS) Conversion of type 'AxiosStatic' to type 'Mock<any, any>'may be a mistake because neither type sufficiently overlaps with theother. If this was intentional, convert the expression to 'unknown'first. Type 'AxiosStatic' is missing the following properties fromtype 'Mock<any, any>': getMockName, mock, mockClear, mockReset, and 12more.
Solved it by specifying as axios as unknown as jest.Mock
AxiosRequest.test.tsx
import axios from 'axios';import { MediaByIdentifier } from '../api/mediaController';jest.mock('axios', () => jest.fn());test('Test AxiosRequest',async () => { const mRes = { status: 200, data: 'fake data' }; (axios as unknown as jest.Mock).mockResolvedValueOnce(mRes); const mock = await MediaByIdentifier('Test'); expect(mock).toEqual(mRes); expect(axios).toHaveBeenCalledTimes(1);});
mediaController.ts:
import { sendRequest } from './request'import { AxiosPromise } from 'axios'import { MediaDto } from './../model/typegen/mediaDto';const path = '/api/media/'export const MediaByIdentifier = (identifier: string): AxiosPromise<MediaDto> => { return sendRequest(path + 'MediaByIdentifier?identifier=' + identifier, 'get');}
request.ts:
import axios, { AxiosPromise, AxiosRequestConfig, Method } from 'axios';const getConfig = (url: string, method: Method, params?: any, data?: any) => { const config: AxiosRequestConfig = { url: url, method: method, responseType: 'json', params: params, data: data, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' }, } return config;}export const sendRequest = (url: string, method: Method, params?: any, data?: any): AxiosPromise<any> => { return axios(getConfig(url, method, params, data))}