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

如何测试axios实例myApi是否被调用及在测试中访问该实例

测试axios实例myApi的调用情况

步骤1:确保实例和函数可被测试访问

原代码中的myApi和auth函数未导出,测试文件无法直接访问,需要先在模块中导出它们:

import axios from 'axios';

// 导出myApi实例
export const myApi = axios.create({
  baseURL: '你的基础URL'
});

// 导出auth函数
export async function auth(email, password) {
  const request = await myApi.post('/authorization', { email, password });
  return request;
}

步骤2:用Jest测试实例调用(两种常见方式)

方式一:直接监听实例的post方法

通过jest.spyOn监听myApi.post,模拟返回值后断言调用情况:

import { auth, myApi } from './你的模块路径';

// 监听myApi的post方法,模拟成功响应
jest.spyOn(myApi, 'post').mockResolvedValue({ data: '模拟响应数据' });

test('auth函数正确调用myApi.post', async () => {
  // 执行auth函数
  await auth('test@example.com', 'test123');

  // 断言post方法被调用1次
  expect(myApi.post).toHaveBeenCalledTimes(1);
  // 断言调用参数符合预期
  expect(myApi.post).toHaveBeenCalledWith('/authorization', {
    email: 'test@example.com',
    password: 'test123'
  });
});

方式二:Mock整个axios模块

如果不想直接依赖myApi的导出,可以mock整个axios模块,验证create返回的实例方法调用:

import axios from 'axios';
import { auth } from './你的模块路径';

// Mock整个axios模块
jest.mock('axios');

test('auth通过myApi实例发起post请求', async () => {
  // 模拟axios.create返回的实例及post方法
  const mockPost = jest.fn().mockResolvedValue({ data: '模拟响应数据' });
  axios.create.mockReturnValue({ post: mockPost });

  await auth('test@example.com', 'test123');

  // 可选:验证axios.create的调用参数
  expect(axios.create).toHaveBeenCalledWith({ baseURL: '你的基础URL' });
  // 验证post方法的调用情况
  expect(mockPost).toHaveBeenCalledTimes(1);
  expect(mockPost).toHaveBeenCalledWith('/authorization', {
    email: 'test@example.com',
    password: 'test123'
  });
});

其他测试框架的思路

如果使用Mocha+Sinon这类框架,核心逻辑一致:

  • 用sinon.spy监听myApi.post方法
  • 执行auth函数后,断言spy的调用次数和参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:31:03