Some checks reported errors
continuous-integration/drone/push Build was killed
- 搭建 api、auth、utils 等逻辑模块 - 通过 tsc、eslint、vitest 测试验证 BREAKING CHANGE: 新镜像分支
75 lines
1.6 KiB
TypeScript
75 lines
1.6 KiB
TypeScript
/**
|
|
* HTTP客户端Mock
|
|
* 用于模拟axios行为
|
|
*/
|
|
|
|
import vi from 'vitest';
|
|
import type { AxiosResponse, AxiosError } from 'axios';
|
|
import { createMockApiResponse, createMockErrorResponse } from './data-factory';
|
|
|
|
// 模拟axios响应
|
|
export function createMockAxiosResponse<T>(data: T, status = 200): AxiosResponse<T> {
|
|
return {
|
|
data,
|
|
status,
|
|
statusText: 'OK',
|
|
headers: {},
|
|
config: {} as any
|
|
};
|
|
}
|
|
|
|
// 模拟axios错误
|
|
export function createMockAxiosError(message: string, code = 'ERR_BAD_REQUEST', status = 400): AxiosError {
|
|
const error = new Error(message) as AxiosError;
|
|
error.code = code;
|
|
error.response = {
|
|
data: createMockErrorResponse(message, status),
|
|
status,
|
|
statusText: 'Bad Request',
|
|
headers: {},
|
|
config: {} as any
|
|
};
|
|
return error;
|
|
}
|
|
|
|
// 创建模拟的axios实例
|
|
export function createMockAxios() {
|
|
return {
|
|
get: vi.fn(),
|
|
post: vi.fn(),
|
|
put: vi.fn(),
|
|
delete: vi.fn(),
|
|
patch: vi.fn(),
|
|
request: vi.fn(),
|
|
interceptors: {
|
|
request: {
|
|
use: vi.fn(),
|
|
eject: vi.fn()
|
|
},
|
|
response: {
|
|
use: vi.fn(),
|
|
eject: vi.fn()
|
|
}
|
|
},
|
|
defaults: {
|
|
headers: {
|
|
common: {},
|
|
get: {},
|
|
post: {},
|
|
put: {},
|
|
delete: {}
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
// 模拟成功响应
|
|
export function mockSuccessResponse<T>(data: T) {
|
|
return Promise.resolve(createMockAxiosResponse(createMockApiResponse(data)));
|
|
}
|
|
|
|
// 模拟失败响应
|
|
export function mockErrorResponse(message: string, status = 400) {
|
|
return Promise.reject(createMockAxiosError(message, 'ERR_BAD_REQUEST', status));
|
|
}
|