You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest模拟Axios的get请求响应并解决测试报错?

问题原因

  • axios.get.mockResolvedValue(mockResp)的作用是配置mock函数返回一个决议值为mockResp的Promise对象,而非直接返回mockResp本身。
  • toHaveReturnedWith校验的是mock函数的同步返回值,你当前场景下它拿到的实际返回是Promise实例,和你预期的普通对象自然匹配失败。
  • 此外当前测试代码没有等待异步逻辑执行完成,就算要校验异步返回结果也会存在时序问题。

解决方案

方案1:使用异步匹配器直接校验Promise决议值

Jest提供了专门针对异步mock的匹配器toHaveResolvedValue,不需要额外处理就能直接校验mock函数返回的Promise的最终决议值:

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

describe('GET /searchLocation', () => {
    it('should return mock object', async () => { // 测试用例声明为async
        const mockResp = { test: 'test' };
        axios.get.mockResolvedValue(mockResp);
        axios.get('/');
        expect(axios.get).toHaveBeenCalledWith('/'); 
        // 改用异步匹配器,前面加await等待匹配完成
        await expect(axios.get).toHaveResolvedValue(mockResp); 
    });
});

方案2:等待请求执行完成后校验实际返回结果

如果你的测试需要拿到返回结果做后续校验,直接等待axios.get返回的Promise决议即可:

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

describe('GET /searchLocation', () => {
    it('should return mock object', async () => {
        const mockResp = { test: 'test' };
        axios.get.mockResolvedValue(mockResp);
        const result = await axios.get('/'); // 等待Promise决议拿到实际返回值
        expect(axios.get).toHaveBeenCalledWith('/'); 
        expect(result).toEqual(mockResp); // 直接校验返回值即可
    });
});

内容的提问来源于stack exchange,提问作者ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:06:03