如何便捷创建AxiosError对象用于前端单元测试场景?
便捷创建AxiosError对象的两种方案
方案1:使用Axios官方内置的构造函数
Axios库本身就对外导出了AxiosError类,你可以直接实例化生成符合类型定义的实例,不需要手动拼装所有属性,从v0.22.0版本开始支持该用法。
示例代码如下:
import { AxiosError } from 'axios'; describe('isEmailConflict', () => { function newConflictError(): AxiosError<{ type?: string; message?: string }> { // 构造函数参数依次为:错误信息、错误码、请求配置、请求对象、响应对象 return new AxiosError( 'Conflict', 'ERR_BAD_REQUEST', {}, {}, { data: { type: 'aa', message: 'bb' }, status: 409, statusText: 'Conflict', headers: {}, config: {}, } ); } it('should return true if the passed error is of type email already used', () => { const error = newConflictError(); // 测试逻辑 }); });
生成的实例会自动带上isAxiosError: true、toJSON等默认属性,完全符合AxiosError的类型约束,不需要手动补充。
方案2:封装通用测试工厂函数简化调用
如果测试场景中需要频繁生成不同配置的AxiosError,可以封装一个通用的工厂函数,支持按需覆盖属性,减少重复代码:
import { AxiosError, AxiosResponse } from 'axios'; type TestAxiosErrorOptions<T = unknown> = { data?: T; status?: number; statusText?: string; code?: string; message?: string; }; function createTestAxiosError<T = unknown>( options: TestAxiosErrorOptions<T> = {} ): AxiosError<T> { const { data = {}, status = 500, statusText = 'Internal Server Error', code = 'ERR_BAD_RESPONSE', message = 'Request failed' } = options; const response: AxiosResponse<T> = { data, status, statusText, headers: {}, config: {}, }; return new AxiosError(message, code, {}, {}, response); }
使用时只需要传入需要自定义的属性即可:
// 生成409冲突错误 const error = createTestAxiosError({ data: { type: 'aa', message: 'bb' }, status: 409, statusText: 'Conflict' });
这个方案零额外依赖,对测试配置没有侵入性,灵活度更高。
内容的提问来源于stack exchange,提问作者Julien TASSIN
相关产品推荐
相关产品推荐

