Dhiren Punjabi
Dhiren Punjabi

Reputation: 63

axios.create of jest's axios.create.mockImplementation returns undefined

I have written a test for component CategoryListContainer for just testing axios get call in it by mocking axios as below :

CategoryListContainer.test.js

import React from 'react';
import { render, cleanup, waitForElement } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from '../../Store';
import axios from 'axios';
import CategoryListContainer from './CategoryListContainer';

jest.mock('axios', () => ({
  create: jest.fn(),
}));

const products = {
  data: [
    {
      id: '0',
      heading: 'Shirt',
      price: '800',
    },
    {
      id: '1',
      heading: 'Polo tees',
      price: '600',
    },
  ],
};

afterEach(cleanup);
const renderComponent = () =>
  render(
    <Provider store={store()}>
      <CategoryListContainer />
    </Provider>
  );

test('render loading state followed by products', async () => {
  axios.create.mockImplementation((obj) => ({
    get: jest.fn(() => Promise.resolve(products)),
  }));
  const { getByText } = renderComponent();
  await waitForElement(() => {
    expect(getByText(/loading/i)).toBeInTheDocument();
  });
});

As we see that in test 'render loading state followed by products' I wrote mock implemenation for axios.create as axios.create.mockImplementation((obj) => ({ get: jest.fn(() => Promise.resolve(products)), }));

Now when I use axios.create in axiosInstance.js as below :

import axios from 'axios';
const axiosInstance = axios.create({
  headers: {
    Accept: 'application/json',
    ContentType: 'application/json',
    authorization: '',
  },
});
console.log(axiosInstance);
export default axiosInstance;

console.log(axiosInstance) shows undefined and therefore I'm getting the below error on running the test :

TypeError: Cannot read property 'get' of undefined

  4 | const fetchCategories = () => async (dispatch) => {
  5 |   const response = await axiosInstance
> 6 |     .get('/api/category/all')
    |      ^
  7 |     .catch((error) => {
  8 |       dispatch(fetchErrorAction(error));
  9 |       if (error.message.split(' ').pop() == 504) {

console.log src/backendApiCall/axiosInstance.js:9 undefined

I want to understand why console.log(axiosInstance) shows undefined . And the solution to making the test successful with making minimum changes to code .

Upvotes: 0

Views: 3419

Answers (1)

To Luu
To Luu

Reputation: 91

because 'create' return jest function so it does not has '.get'. You can use this

jest.mock('axios', () => {
  return {
    create: () => {
      return {
       get: jest.fn()
     }}
  };
});

then, you can set mock value

axiosInstance.get.mockReturnValueOnce({
  data : {}
})

Upvotes: 5

Related Questions