53

I have the following method in a class:

import axios from 'axios'

public async getData() {
   const resp = await axios.get(Endpoints.DATA.URL)
   return resp.data
}

Then I am trying to set up a Jest test that does this:

jest.mock('axios')

it('make api call to get data', () => {
   component.getData()
   expect(axios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})

The problem is that because I am not mocking the return value, then it gives an error for resp.data because I'm calling data on null or undefined object. I spent at least 2 hours trying various ways to get this working but I can't find a way such that I can mock axios.get with some return value.

Jest's documentation uses JavaScript so they give this example axios.get.mockResolvedValue(resp) but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript.

Also, if you know other good testing library for React other than Jest that does this stuff easily for TypeScript, feel free to share.

8 Answers 8

119

In start of file:

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

Now you can use it as usual mock:

mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue({ data: {} });
4
  • 4
    I did exactly the same thing, but typescript is blaming my { data: null } with this error: error TS2345: Argument of type '{ data: null; }' is not assignable to parameter of type '(<T = any>(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise<T>) | PromiseLike<(<T = any>(url: string, config?: AxiosRequestConfig | undefined) => AxiosPromise<T>)>'. No idea why it doesn't work... Apr 9, 2019 at 13:36
  • 1
    you can try to type this or make any: { data: null } as any Apr 12, 2019 at 12:21
  • Thank you for this. Can you please tell me your thought process or where did you find this solution. I want to understand this to be a better developer. const mockedAxios = axios as jest.Mocked<typeof axios> Apr 16 at 16:07
  • Cannot read properties of undefined (reading 'interceptors') and requestInstance.interceptors... Jul 24 at 5:45
22

If you want to use jest.mock with "no-any" try this:

import axios, { AxiosStatic } from 'axios'

interface AxiosMock extends AxiosStatic {
  mockResolvedValue: Function
  mockRejectedValue: Function
}

jest.mock('axios')
const mockAxios = axios as AxiosMock

it('make api call to get data', () => {
   // call this first
   mockAxios.mockResolvedValue(yourValue)

   component.getData()
   expect(mockAxios.get).toHaveBeenCalledWith(Endpoints.DATA.URL)
})
3
  • 2
    This works and doesn't require another library, should be accepted answer
    – mpd
    Mar 4, 2019 at 23:03
  • this approach works for me too, without the need to add new libraries. The only thing I am a bit stuck on is how to make it so that I don't have to repeat the same code in different test files.. will look into it and update the comment (hopefully)
    – mikey
    Jun 28, 2021 at 4:41
  • TypeError: Cannot read properties of undefined (reading 'interceptors') and requestInstance.interceptors Jul 24 at 5:48
11

As of Jest 24.9.0 here is how it works correctly typing both axios and Jest properties.

What we would like for a typed mock is that the mocked object type contains the union of the mocked object type and the type of Jest mocks. As far as I seen non of the current answers enable that.

jest.MockedFunction

jest.MockedClass

import axios from 'axios';
jest.mock('axios');

const mockedAxios = axios as jest.MockedFunction<typeof axios>;

mockedAxios.mockResolvedValue({ status: 200, data: 'mockResponse' });

// Or:
(mockedAxios.get as jest.MockedFunction<typeof mockedAxios.get>).mockResolvedValue('mockResponse');

As you can see, you can either manually cast what you need or you'll need something to traverse all axios properties/methods to type everything.

To do that (deep mock types) you can use jest.mocked() introduced in Jest 27.4.0

import axios from 'axios';
jest.mock('axios');

const mockedAxios = jest.mocked(axios, true); 

mockedAxios.mockImplementation() // correctly typed
mockedAxios.get.mockImplementation() // also correctly typed
1
  • As of Jest 29.0.0, jest.mocked is default deep mocked. To invert this behavior, use jest.mocked(axios, {shallow:true})
    – jloh
    Apr 26 at 13:02
8

This is what I personally always use.

import axios from 'axios';
jest.mock('axios')

it('...', () => {
  (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve({}));
  // test here
  expect(axios.get).toHaveBeenCalled()
}
7

I kept running into is not a function issues. If the accepted answer doesn't work for you, then try importing axios with a capital A ie. Axios.

import Axios from 'axios';
jest.mock('Axios');
const mockedAxios = Axios as jest.Mocked<typeof Axios>;
1
  • I have no idea why it works, but it helped me - thank you!
    – mrCod3r
    Nov 10, 2022 at 9:50
3

but I can't call mockResolvedValue because that method does not exist on axios.get in TypeScript

You can use an assertion:

(axios.get as any).mockResolvedValue(resp)
3
  • 2
    The project has a ts-lint rule "no-any": true Jul 11, 2018 at 16:42
  • add a tslint ignore on the line before
    – basarat
    Jul 12, 2018 at 6:03
  • 2
    1. That's not going to be ideal as the project grows and more asynchronous calls are added. 2. I am using TypeScript for its strong type system and I don't want to circumvent it. Jul 13, 2018 at 5:36
2

I found a neat solution using the sinon library npm install sinon @types/sinon --save-dev.

Then the testing code becomes:

let component: Component
let axiosStub: SinonStub

beforeAll(() => {
    component = new Component({})
    axiosStub = sinon.stub(axios, 'get')
})

afterAll(() => {
    axiosStub.restore()
})

it('make api call to get data', async () => {
    // set up behavior
    axiosStub.withArgs(Endpoints.DATA.URL).returns({data: []})

    // method under test
    const res = await component.getData()

    // assertions
    expect(res).toEqual([])
})
0
2

Another option is to use jest.spyOn:

import axios from "axios";

jest.spyOn(axios, "get").mockImplementation(() => Promise.resolve({data: []}));

This also gives you the benefit of having a mocked method that you can test against, for example:

import axios from "axios";

// ...

const mockedGet = jest
  .spyOn(axios, "get")
  .mockImplementation(() => Promise.resolve({data: []}));

// ...

expect(mockedGet).toBeCalledWith('https://example.api?q=abc&k=123');

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.