Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of Axios mock using jest typescript

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.

like image 253
Stefan Zhelyazkov Avatar asked Jul 11 '18 00:07

Stefan Zhelyazkov


People also ask

How do I test Axios post in Jest?

To test axios in Jest, we can mock the axios dependency. import * as axios from "axios"; jest. mock("axios"); // ... test("good response", () => { axios.

How do you test Axios in React testing library?

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.

Why we use Axios mock adapter?

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.


2 Answers

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: {} });
like image 72
Jan Tumanov Avatar answered Oct 19 '22 07:10

Jan Tumanov


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)
})
like image 27
Adam T. Smith Avatar answered Oct 19 '22 07:10

Adam T. Smith