Search code examples
reactjsjestjsaxiosjest-fetch-mock

How to mock Axios service wrapper using JEST


I'm using JEST testing framework to write test cases for my React JS application. I'm using our internal axios wrapper to make service call. I would like to mock that wrapper service using JEST. Can someone help me on this ?

import Client from 'service-library/dist/client';
import urls from './urls';
import { NODE_ENV, API_VERSION } from '../screens/constants';
const versionHeader = 'X-API-VERSION';
class ViewServiceClass extends Client {
  getFiltersList(params) {
    const config = {
      method: urls.View.getFilters.requestType,
      url: urls.View.getFilters.path(),
      params,
      headers: { [versionHeader]: API_VERSION },
    };
    return this.client.request(config);
  }
const options = { environment: NODE_ENV };
const ViewService = new ViewServiceClass(options);
export default ViewService;

Above is the Service Implementation to make API call. Which I'm leveraging that axios implementation from our internal library.

getFiltersData = () => {
    const params = {
      filters: 'x,y,z',
    };
    let {
      abc,
      def,
      ghi
    } = this.state;
    trackPromise(
      ViewService.getFiltersList(params)
        .then((result) => {
          if (result.status === 200 && result.data) {
            const filtersJson = result.data;
            
        .catch(() =>
          this.setState({
            alertMessage: 'No Filters Data Found. Please try after some time',
            severity: 'error',
            showAlert: true,
          })
        )
    );
  };

I'm using the ViewService to get the response, and I would like to mock this service. Can someone help me on this ?


Solution

  • You would need to spy your getFiltersList method from ViewServiceClass class.

    Then mocking some response data (a Promise), something like:

    import ViewService from '..';
    
    const mockedData = {
      status: 'ok',
      data: ['some-data']
    };
    
    const mockedFn = jest.fn(() => Promise.resolve(mockedData));
    
    let getFiltersListSpy;
    
    // spy the method and set the mocked data before all tests execution
    beforeAll(() => {
      getFiltersListSpy = jest.spyOn(ViewService, 'getFiltersList');
      getFiltersListSpy.mockReturnValue(mockedFn);
    });
    
    // clear the mock the method after all tests execution
    afterAll(() => {
      getFiltersListSpy.mockClear();
    });
    
    // call your method, should be returning same content as `mockedData` const
    test('init', async () => {
      const response = await ViewService.getFiltersList();
      expect(response).toEqual(mockedData);
    });
    

    P.D: You can pass params to the method, but you will need to configure as well the mockedData as you wish.