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.
To test axios in Jest, we can mock the axios dependency. import * as axios from "axios"; jest. mock("axios"); // ... test("good response", () => { axios.
We have to set up Jest to mock axios. Simply create a folder __mocks__ in the src directory, we name the file axios. js with the below code. Next, we have to set up the afterEach cleanup with Jest, so that we don't have to repeat this in each of our test files.
Axios Mock Adapter Instance — This is used to define the Mock request handling code to define the Mock data. Axios Mock Instance — This is used within React to invoke the API as a typical Axios instance.
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: {} });
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With