← Back to blog

How to mock axios in jest with Typescript

This article explains the correct way how to mock axios in jest with typescript

If you look to jest documentation for mocking modules you will find how to mock axios library.

But this approach is working only in plain JavaScript, typescript will complain that such method is not existing in axios:

axios error

So to explicitly tell that we are working with mock we should do next:

First, import axios and assign typed mock to new variable:

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

Now you can use this mocked variable as axios mock:

mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue({ data: {} });

So after this simple procedure Typescript will not complain anymore and will see correct mock methods: correct axios mock