Jest+Axios单元测试通过却出现Network Error警告问题求助
解决Jest测试Axios工具类时的Network Error警告
我有一个用Axios执行REST调用的工具类,编写Jest单元测试时,所有用例都能通过,但始终会弹出一条「Network Error」的警告,错误详情如下:
C:/home/dev/node_modules/axios/lib/core/createError.js:16 var error = new Error(message); Error: Network Error at createErrorC:/home/dev/node_modules/axios/lib/core/createError.js:16 config: { // .... header: { Accept: 'application/json, text/plain, */*' }, withCredentials: true, responseType: 'json', method: 'get', url: 'http://mock.rest.server.com:1234/rest/user/data/adam', data: undefined }, request: XMLHttpRequest {}, response: undefined, isAxiosError: true, toJSON: [Function: toJSON]
对应的工具类代码(utility.ts):
import axios, { AxiosResponse } from 'axios' axios.defaults.withCredentials = true; axios.defaults.responseType = 'json'; export class UserUtils { public getUserConfig(userName: string): Promise<AxiosResponse> { if(!userName) { return; } return axios.get('http://mock.rest.server.com:1234/rest/user/data/' + userName); } }
测试代码(utility.test.ts):
import axios from 'axios'; import { UserUtils } from '../../utility'; describe("Utility test", () => { const utils = new UserUtils(); jest.mock('axios', () => { return { post: jest.fn(), get: jest.fn() } } // clear all mocks beforEach(() => { jest.clearAllMocks(); jest.restoreAllMocks(); }); test("get user data",() => { jest.spyOn(axios, 'get'); utils.getUserConfig('adam') .then(repsonse => { expect(axios.get).toHaveBeenCalledWith('http://mock.rest.server.com:1234/rest/user/data/adam'); }); }); });
问题根源
- Mock不完整:只mock了Axios的
get/post方法,但工具类里设置的全局默认配置(withCredentials、responseType)没被mock覆盖,测试时仍会尝试初始化真实Axios实例,触发网络请求逻辑。 - Mock未返回有效Promise:当前的
axios.getmock没有返回resolved状态的Promise,调用getUserConfig后Promise处于pending/rejected状态,触发Axios错误处理,抛出Network Error。 - 异步逻辑未正确处理:测试没使用
async/await或返回Promise,Jest可能在异步回调执行前就结束测试,同时导致Promise未被正确resolve。 - 拼写错误:
beforEach应为beforeEach,且jest.restoreAllMocks没必要,因为已经用jest.mock完全替换了Axios模块。
修复方案
修改测试代码,完善Axios的mock逻辑并正确处理异步测试:
import axios from 'axios'; import { UserUtils } from '../../utility'; // 完整mock Axios模块,包含默认配置和get方法的返回值 jest.mock('axios', () => ({ defaults: { withCredentials: true, responseType: 'json' }, get: jest.fn().mockResolvedValue({ data: {} }), // 返回resolved状态的Promise post: jest.fn() })); describe("Utility test", () => { const utils = new UserUtils(); beforeEach(() => { jest.clearAllMocks(); // 仅清理mock的调用记录 }); // 用async/await处理异步测试,确保Jest等待异步操作完成 test("get user data", async () => { await utils.getUserConfig('adam'); expect(axios.get).toHaveBeenCalledWith('http://mock.rest.server.com:1234/rest/user/data/adam'); }); });
额外提示
- 如果要模拟错误场景,可将
mockResolvedValue换成mockRejectedValue,配合expect().rejects.toThrow()进行测试。 - 工具类中
getUserConfig方法在!userName时返回undefined,不符合Promise<AxiosResponse>的类型声明,建议改成return Promise.reject(new Error('userName is required'))或调整类型,避免类型错误。
内容的提问来源于stack exchange,提问作者Oam Psy
相关产品推荐
相关产品推荐

