Let's test out this interesting class:
//RequestHandler.js
import axios, {AxiosInstance} from 'axios';
import settings from './settings';
const axiosHandler: AxiosInstance = axios.create({
baseURL: 'http://localhost:8081',
});
export default class RequestHandler {
public async getData<$ResponseType = any>(url: string): Promise<void> {
const response = await axiosHandler.get(url);
return response.data;
}
}
While attempting to create a test file for this class, I encountered some challenges when it came to mocking axios. Despite trying various methods such as spyOn and automatic mocks, I couldn't get them to work effectively. Below is a snippet from the unsuccessful test file that has me puzzled:
// RequestHandler.test.js
import axios from 'axios';
import RequestHandler from './RequestHandler';
interface ITestDataStructure {
content: string
}
jest.mock('axios');
describe('RequestHandler Testing', () => {
it('should correctly utilize axios get with the specified relativeUrl', async () => {
const mockedGet = jest.fn();
axios.create.mockReturnValue({
get: mockedGet
});
mockedGet.mockResolvedValueOnce({
content: 'example'
});
const data = await new RequestHandler().getData<ITestDataStructure>('/someEndpoint');
expect(mockedGet.mock.calls.length).toEqual(1);
expect(data).toEqual({
content: 'example'
});
});
});
Upon running the test, an error message is displayed -
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/services/RequestHandler.test.ts:15:18 - error TS2339: Property 'mockReturnValue' does not exist on type '(options?: AxiosRequestConfig | undefined) => AxiosInstance'.
15 axios.create.mockReturnValue({
This error is understandable since the axios type definition doesn't include the 'mockReturnValue' method for 'create'. How can we inform TypeScript that jest has made changes in this case?