如何使用Jest测试基于Axios封装的HttpClient?
用Jest测试封装的HTTP Post方法
你封装的httpService代码如下:
import axios from 'axios' const httpClient = axios.create({ headers: { common: { 'Content-Type': 'application/json' } } }) export async function post(url, data) { try { const response = await httpClient.post(url, data) return response.data } catch (error) { console.log(error) throw new Error('Error in POST request') } }
要测试这个post方法的请求成功场景,核心是用Jest mock axios模块,避免发送实际网络请求,具体实现如下:
测试文件实现(示例:httpService.test.js)
import axios from 'axios'; import { post } from './httpService'; // 替换为你的实际文件路径 // Mock 整个axios模块 jest.mock('axios'); describe('httpService post method', () => { it('should return response data when post request succeeds', async () => { // 定义测试用的参数和模拟返回值 const testUrl = 'http://test.com/api'; const testRequestData = { username: 'testUser', password: '123456' }; const mockResponseData = { code: 200, message: '请求成功', data: { token: 'abcd1234' } }; // 模拟axios.create的返回对象,以及post方法的成功响应 const mockHttpClient = { post: jest.fn().mockResolvedValue({ data: mockResponseData }) }; axios.create.mockReturnValue(mockHttpClient); // 调用待测试的post方法 const result = await post(testUrl, testRequestData); // 断言验证逻辑 // 确认axios.create被正确调用,配置参数符合预期 expect(axios.create).toHaveBeenCalledTimes(1); expect(axios.create).toHaveBeenCalledWith({ headers: { common: { 'Content-Type': 'application/json' } } }); // 确认post方法被传入正确的URL和请求数据调用 expect(mockHttpClient.post).toHaveBeenCalledTimes(1); expect(mockHttpClient.post).toHaveBeenCalledWith(testUrl, testRequestData); // 确认返回结果与模拟的响应数据一致 expect(result).toEqual(mockResponseData); }); });
关键逻辑说明
jest.mock('axios')会自动替换整个axios模块为Jest mock函数,避免触发真实网络请求- 手动模拟
axios.create的返回值,让它返回带有mock post方法的对象,用mockResolvedValue模拟请求成功的Promise - 通过多层断言,从axios初始化、post调用参数到最终返回值,全面验证代码逻辑的正确性
内容的提问来源于stack exchange,提问作者isadfrn
相关产品推荐
相关产品推荐

