Search code examples
javascriptpromisejestjsaxios-mock-adapter

How to resolve promise and spy on a function inside axios


function getusers(config){
     const {successCB} = config;
     return axios.get(url, params)
      .then(response => {
        successCB(response.data, config);
      });
}

************************ UT ******************************

const mock = new MockAdapter(axios);
const successCB = jest.fn();

mock.onGet(url).reply(200, 'success');
const axiosSpy = jest.spyOn(axios, 'get');
const successCBSpy = jest.spyOn(config, 'successCB');

getUsers({successCB});

axiosSpy is success from below code

expect(axiosSpy).toHaveBeenCalled();

But it's not reaching inside to resolve with results for successCB

expect(successCBSpy).toHaveBeenCalled();

Throwing error as: successCB never called

What am I doing wrong and what should I expect here?

I am only able to use ES6 solutions only.


Solution

  • Make sure you return the Promise from getusers so you can await it in your test.

    Here is a complete working example:

    const axios = require('axios');
    const MockAdapter = require('axios-mock-adapter');
    
    const url = 'test-url';
    const params = {};
    
    function getusers(config) {
      const { successCB } = config;
      return axios.get(url, params)  // <= return the Promise
        .then(response => {
          successCB(response.data, config);
        });
    }
    
    test('getusers', async () => {  // <= async test function
      const mock = new MockAdapter(axios);
      const successCB = jest.fn();
    
      mock.onGet(url).reply(200, 'success');
      const axiosSpy = jest.spyOn(axios, 'get');
    
      await getusers({ successCB });  // <= await the Promise
    
      expect(axiosSpy).toHaveBeenCalled();  // Success!
      expect(successCB.mock.calls[0][0]).toBe('success');  // Success!
    })
    

    Update

    If async/await syntax is not an option then you can do the assertions in a then callback and return the resulting Promise from the test so Jest knows to wait for it:

    test('getusers', () => {
      const mock = new MockAdapter(axios);
      const successCB = jest.fn();
    
      mock.onGet(url).reply(200, 'success');
      const axiosSpy = jest.spyOn(axios, 'get');
    
      return getusers({ successCB }).then(() => {
        expect(axiosSpy).toHaveBeenCalled();  // Success!
        expect(successCB.mock.calls[0][0]).toBe('success');  // Success!
      });
    })