如何在Jest测试中Mock类内部的Axios实例
Jest测试依赖Axios的客户端类(无需真实API密钥)
要实现你的测试需求,核心思路是用Jest模拟Axios的行为,完全规避真实网络请求,同时验证请求细节和响应映射逻辑。下面是具体实现步骤:
1. 模拟Axios模块
首先在测试文件顶部用Jest mock整个axios模块,这样我们可以完全控制它的行为:
jest.mock('axios');
2. 测试API密钥是否正确附加到请求头
我们可以断言axios.create被调用时,传入的配置里包含正确的X-Api-Key头。假设测试文件为example-client.test.js:
import axios from 'axios'; import { ExampleClient } from './example-client'; import { Countries, Languages } from './constants'; describe('ExampleClient', () => { const mockApiKey = 'test-api-key-123'; beforeEach(() => { // 重置所有mock调用记录,避免测试用例互相干扰 jest.clearAllMocks(); }); test('初始化时正确设置Axios请求头', () => { new ExampleClient({ apiKey: mockApiKey, defaultCountry: Countries.Canada, defaultLanguage: Languages.French }); // 断言axios.create被调用,且配置正确 expect(axios.create).toHaveBeenCalledWith({ baseURL: 'https://example-api.com', headers: { 'Content-Type': 'application/json', 'X-Api-Key': mockApiKey } }); }); });
3. 验证接口是否被正确调用
假设你的ExampleClient有一个getUser方法,内部调用this.client.get('/users/:id'),我们可以mock这个get方法并断言调用细节:
// 先给ExampleClient添加示例API方法(对应你的实际业务方法) export class ExampleClient { // ... 原有构造函数代码 ... async getUser(userId: string) { const response = await this.client.get(`/users/${userId}`); return this.mapUserResponse(response.data); } private mapUserResponse(rawData: any) { return { id: rawData.id, fullName: `${rawData.first_name} ${rawData.last_name}`, email: rawData.email }; } } // 测试用例 test('getUser方法正确调用目标接口', async () => { const mockUserId = 'user-456'; const mockAxiosGet = jest.fn().mockResolvedValue({ data: {} }); // 让axios.create返回带有mock get方法的对象 (axios.create as jest.Mock).mockReturnValue({ get: mockAxiosGet }); const client = new ExampleClient({ apiKey: mockApiKey }); await client.getUser(mockUserId); // 断言get方法被调用,且URL正确 expect(mockAxiosGet).toHaveBeenCalledWith(`/users/${mockUserId}`); });
4. 测试响应到可读对象的映射逻辑
通过mock接口返回的原始数据,验证客户端的映射方法是否能正确转换为预期对象:
test('正确映射API响应到自定义对象', async () => { const mockRawUser = { id: 'user-456', first_name: 'John', last_name: 'Doe', email: 'john.doe@example.com' }; const mockAxiosGet = jest.fn().mockResolvedValue({ data: mockRawUser }); (axios.create as jest.Mock).mockReturnValue({ get: mockAxiosGet }); const client = new ExampleClient({ apiKey: mockApiKey }); const user = await client.getUser('user-456'); // 断言映射后的对象符合预期 expect(user).toEqual({ id: 'user-456', fullName: 'John Doe', email: 'john.doe@example.com' }); });
关键注意点
- 每次测试前用
jest.clearAllMocks()重置mock调用记录,确保测试用例独立 - 如果客户端有多个API方法,只需为每个方法编写对应的mock和断言逻辑
- 可以用
mockRejectedValue模拟接口错误场景,测试客户端的错误处理逻辑
内容的提问来源于stack exchange,提问作者FlushBG
相关产品推荐
相关产品推荐

