skip to Main Content

My jest test mock of an axios get returns back undefined as the response and I am not sure what I am doing wrong?

My component that has the axios call is shown below:

const fetchResults = (paramsApi) => {
  Service()
  .getResults(object)
  .then((response) => {
    console.log("calling.....", response); // undefined for response, why?
    let results = response.data.results;
    // more code below but unnecessary to show since response is undefined

Jest test class:

const axios = require("axios");
jest.mock("axios");

describe('AgGridResults', () => {
  beforeEach(async () => {
    axios.get = jest.fn().mockResolvedValue(
      {
        data: {
          results: {
            M0: {
              value: [
                'Source Id'
              ]
            }
          }
        }
      },
    );
    render(<AgGridResults searchObject={...} />);
    await waitFor(() => expect(screen.getByText('Actions')).toBeInTheDocument())
  });

  test('AgGridResults', () => {
    expect(screen.getByText('Actions')).toBeInTheDocument();
  });
});

import axios from 'axios';

function Service() {
  return {
    getResults: async (searchObject) => {
      let urlString = UrlUtility().convert(searchObject);
      if (searchObject && urlString) {
        return await axios.get('/api/' + urlString + '&pageLength=50');
      }
    },
    getAgreementTypes: async (searchTerm) => {
      return await axios.get('/api/' + 'searchString=' + searchTerm);
    },
  };
}

export default Service;

2

Answers


  1. Mocking Axios when your component doesn’t actually use it creates a brittle coupling. If you ever changed the Service implementation, your tests would break.

    I would instead mock Service for your component test

    jest.mock("./path/to/service", () => ({
      __esModule: true,
      default: () => ({
        getResults: async () => ({
          data: { results: { M0: { value: ["Source ID"] } } },
        }),
      }),
    }));
    
    Login or Signup to reply.
  2. Try this out.

    import axios from 'axios';
    import MockAdapter from 'axios-mock-adapter';
    
    describe('EcgDataProcessor (e2e)', () => {
      
      let axiosMock: any;
    
      beforeAll(async () => {
        axiosMock = new MockAdapter(axios);
        axiosMock.onGet('https://path').reply(200, "response");
      })
      
    });
    

    https://www.npmjs.com/package/axios-mock-adapter

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search