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

如何使用Sinon模拟整个axios对象?

用Sinon Stub axios默认函数调用

当你直接调用axios()(而非axios.post()这类方法)时,需要针对axios本身这个函数进行Stub,而不是它的属性方法。具体实现如下:

基础Stub实现

直接Stub axios对象本身(因为axios默认导出的就是一个可调用的函数),指定它的返回值:

const sinon = require('sinon');
const axios = require('axios');

// 定义模拟响应
const mockResponse = { data: '模拟返回数据', status: 200 };

// Stub axios默认函数调用,让它返回模拟响应
const axiosStub = sinon.stub(axios).resolves(mockResponse);

// 测试你的代码
async function testAxiosCall() {
  const response = await axios({
    method: 'get',
    url: '/api/test',
    headers: { 'Content-Type': 'application/json' }
  });
  console.log(response.data); // 输出:模拟返回数据
}

testAxiosCall();

// 验证调用是否符合预期
sinon.assert.calledOnce(axiosStub);
sinon.assert.calledWith(axiosStub, sinon.match({
  method: 'get',
  url: '/api/test'
}));

根据不同参数返回不同结果

如果需要根据传入的配置(比如method、url)返回不同的模拟响应,可以结合withArgs和sinon.match来实现:

const axiosStub = sinon.stub(axios);

// 当调用axios({ method: 'post', url: '/api/submit' })时返回成功响应
axiosStub.withArgs(sinon.match({ method: 'post', url: '/api/submit' }))
  .resolves({ data: '提交成功', status: 201 });

// 当调用axios({ method: 'get', url: '/api/data' })时返回数据列表
axiosStub.withArgs(sinon.match({ method: 'get', url: '/api/data' }))
  .resolves({ data: [{ id: 1, name: '测试数据' }], status: 200 });

测试后恢复Stub

为了避免Stub影响其他测试用例,记得在测试结束后恢复原函数:

// 在测试用例的清理阶段执行
afterEach(() => {
  axiosStub.restore();
});

内容的提问来源于stack exchange,提问作者Nandanunni A S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:03:26