client.test.ts
9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ApiError, isApiError, createApiClient } from './client';
import axios, { type AxiosRequestConfig } from 'axios';
// Note: Tests for createApiClient request handling use axios mock
// to verify success and error response handling.
// Mock axios for request tests (只 mock default.create,保留真实的 axios)
vi.mock('axios', async () => {
const actual = await vi.importActual<typeof axios>('axios');
return {
default: {
...actual,
create: vi.fn(() => ({
request: vi.fn(),
})),
},
};
});
// 真实 axios 配置合并测试 - 使用真实 axios 实例验证 client.ts 的实现
describe('axios FormData 与 JSON 配置合并边界测试', () => {
// 这些测试验证 createApiClient 在处理 FormData 和 JSON 时的正确行为
// 注意:Node.js 测试环境中 axios 对 FormData 的处理与浏览器不同
// 在浏览器中,axios 会自动为 FormData 生成 multipart/form-data; boundary=...
// 在 Node.js 中,axios 默认转换为 x-www-form-urlencoded
// 核心验证:FormData 请求不应该继承 application/json Content-Type
it('createApiClient FormData 上传请求不继承 application/json Content-Type', async () => {
const realAxios = await vi.importActual<typeof import('axios')>('axios');
let capturedConfig: unknown = null;
const axiosInstance = realAxios.default.create({
baseURL: '/api/v1',
timeout: 30000,
// 不设置默认 Content-Type(模拟修复后的 client.ts)
adapter: async (config) => {
capturedConfig = config;
return Promise.resolve({
data: { code: 200, message: 'success', data: { file_url: 'https://example.com/file.png' } },
status: 200,
statusText: 'OK',
headers: {},
config,
});
},
});
const formData = new FormData();
formData.append('file', new File(['test content'], 'test.png', { type: 'image/png' }));
formData.append('usage_type', 'methodology_icon');
// FormData 不设置 Content-Type(空 headers),让 axios 自动处理
const headers = formData instanceof FormData ? {} : { 'Content-Type': 'application/json' };
await axiosInstance.post('/official-site-upload/upload', formData, { headers });
expect(capturedConfig).not.toBeNull();
const config = capturedConfig as AxiosRequestConfig;
const contentType = config.headers?.['Content-Type'] || config.headers?.['content-type'];
// 核心验证:Content-Type 不应该是 application/json
// 在浏览器中会是 multipart/form-data; boundary=...
// 在 Node.js 测试环境中可能是 x-www-form-urlencoded 或 undefined
expect(contentType).not.toBe('application/json');
// data 应该保持为 FormData 类型(在浏览器中会保持原样)
// 在 Node.js 中可能被转换为字符串,但不应该被 JSON.stringify
expect(config.data instanceof FormData || typeof config.data === 'string').toBe(true);
if (typeof config.data === 'string') {
// Node.js 环境下转换为字符串,但不应该是 JSON 格式
expect(config.data).not.toBe(JSON.stringify(formData));
}
});
it('createApiClient JSON POST 请求正确使用 application/json', async () => {
const realAxios = await vi.importActual<typeof import('axios')>('axios');
let capturedConfig: unknown = null;
const axiosInstance = realAxios.default.create({
baseURL: '/api/v1',
timeout: 30000,
adapter: async (config) => {
capturedConfig = config;
return Promise.resolve({
data: { code: 201, message: 'created', data: { id: 1 } },
status: 201,
statusText: 'Created',
headers: {},
config,
});
},
});
const jsonData = { name: 'test' };
const headers = { 'Content-Type': 'application/json' };
await axiosInstance.post('/agents', jsonData, { headers });
expect(capturedConfig).not.toBeNull();
const config = capturedConfig as AxiosRequestConfig;
const contentType = config.headers?.['Content-Type'] || config.headers?.['content-type'];
expect(contentType).toBe('application/json');
expect(typeof config.data).toBe('string');
expect(JSON.parse(config.data as string)).toEqual({ name: 'test' });
});
});
describe('createApiClient request handling', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.clearAllMocks();
});
it('解包 code 200 成功响应', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 200, message: 'success', data: { id: 1, name: 'test' } },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
const result = await client.get('/test');
expect(result).toEqual({ id: 1, name: 'test' });
});
it('解包 code 201 创建成功响应', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 201, message: '创建成功', data: { id: 1, name: 'new' } },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
const result = await client.post('/test', { name: 'new' });
expect(result).toEqual({ id: 1, name: 'new' });
});
it('非 200/201 的业务 code 抛出 ApiError', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 400, message: '参数错误', data: null },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await expect(client.get('/test')).rejects.toThrow('参数错误');
});
it('code 404 抛出 ApiError', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 404, message: '资源不存在', data: null },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await expect(client.get('/test')).rejects.toThrow('资源不存在');
});
it('code 409 抛出 ApiError', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 409, message: '资源冲突', data: null },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await expect(client.post('/test', {})).rejects.toThrow('资源冲突');
});
it('code 500 抛出 ApiError', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 500, message: '服务器内部错误', data: null },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await expect(client.get('/test')).rejects.toThrow('服务器内部错误');
});
it('code 503 抛出 ApiError', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 503, message: '外部服务不可用', data: null },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await expect(client.get('/test')).rejects.toThrow('外部服务不可用');
});
it('FormData 上传不继承 JSON Content-Type,保留 multipart boundary', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 200, message: '上传成功', data: { file_url: 'https://example.com/file.png' } },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
const formData = new FormData();
formData.append('file', new File(['test'], 'test.png', { type: 'image/png' }));
formData.append('usage_type', 'methodology_icon');
await client.post('/official-site-upload/upload', formData);
const requestConfig = mockAxiosInstance.request.mock.calls[0][0];
// FormData 请求不应该有 Content-Type: application/json
// 应该让 axios/浏览器自动生成 multipart/form-data; boundary=...
expect(requestConfig.headers?.['Content-Type']).not.toBe('application/json');
// 请求体应该是原始 FormData,不是 JSON
expect(requestConfig.data).toBe(formData);
});
it('JSON POST 请求保持 Content-Type: application/json', async () => {
const mockAxiosInstance = {
request: vi.fn().mockResolvedValueOnce({
data: { code: 201, message: '创建成功', data: { id: 1 } },
}),
};
vi.mocked(axios.create).mockReturnValueOnce(mockAxiosInstance as any);
const client = createApiClient();
await client.post('/agents', { name: 'test' });
const requestConfig = mockAxiosInstance.request.mock.calls[0][0];
expect(requestConfig.headers?.['Content-Type']).toBe('application/json');
expect(requestConfig.data).toEqual({ name: 'test' });
});
});
describe('isApiError', () => {
it('识别 ApiError 实例', () => {
const error = new ApiError('test', 400);
expect(isApiError(error)).toBe(true);
});
it('非 ApiError 返回 false', () => {
const error = new Error('test');
expect(isApiError(error)).toBe(false);
});
it('null 返回 false', () => {
expect(isApiError(null)).toBe(false);
});
it('undefined 返回 false', () => {
expect(isApiError(undefined)).toBe(false);
});
});
describe('ApiError', () => {
it('包含正确的 message 和 code', () => {
const error = new ApiError('参数错误', 400);
expect(error.message).toBe('参数错误');
expect(error.code).toBe(400);
expect(error.name).toBe('ApiError');
});
});