How to mock Axios get response with jest

Viewed 3002

How do I mock an axios get response? This test is failing with the following error:

Error: expect(jest.fn()).toHaveReturnedWith(expected)

Expected: {"test": "test"}
Received: {}

Number of returns: 1

This is the test I'm running:

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

describe('GET /searchLocation', () => {
    it('should return mock object', () => {
        const mockResp = { test: 'test' };
        axios.get.mockResolvedValue(mockResp);
        axios.get('/');
        expect(axios.get).toHaveBeenCalledWith('/'); //passes
        expect(axios.get).toHaveReturnedWith(mockResp); //fails
    });
});
1 Answers

I think replacing this:

  axios.get.mockResolvedValue(mockResp);

With this:

  axios.get = jest.fn(() => mockResp);

Should help you.

P.S.: this call expect(axios.get) won't wait for promise to resolve.

Related