【问题标题】:How to mock Axios get response with jest如何模拟 Axios 以开玩笑的方式获得响应
【发布时间】:2022-01-04 17:27:24
【问题描述】:

如何模拟 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
    });
});

【问题讨论】:

  • 它没有返回mockResp,它返回了一个promise。但是无论如何断言它返回的内容并没有多大意义,它会返回您刚刚配置的内容。
  • @jonrsharpe 断言只是我试图验证模拟是否有效,而不是对任何东西的真正测试。你的承诺是对的,谢谢 :) 我正在追逐一条红鲱鱼,我的失败在别处!

标签: node.js axios jestjs


【解决方案1】:

我想替换这个:

  axios.get.mockResolvedValue(mockResp);

有了这个:

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

应该能帮到你。

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

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2020-10-20
    • 2019-12-19
    • 2021-06-26
    相关资源
    最近更新 更多