如何模拟 Axios 以开玩笑的方式得到回应

How to mock Axios get response with jest

如何模拟 axios 获得响应?此测试因以下错误而失败:

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

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

Number of returns: 1

这是我的测试 运行:

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
    });
});

我想替换这个:

  axios.get.mockResolvedValue(mockResp);

有了这个:

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

应该能帮到你。

P.S.: 这个调用 expect(axios.get) 不会等待 promise 解决。