apiClient.test.ts
6.07 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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createApiClient, resolveApiBaseURL } from '../api/client';
import { ApiError, isSuccessCode } from '../api/types';
describe('API Client 测试', () => {
const originalFetch = globalThis.fetch;
let mockFetch: ReturnType<typeof vi.fn>;
beforeEach(() => {
mockFetch = vi.fn();
(globalThis as unknown as { fetch: unknown }).fetch = mockFetch;
});
afterEach(() => {
(globalThis as unknown as { fetch: unknown }).fetch = originalFetch;
vi.clearAllMocks();
});
describe('默认配置', () => {
it('默认 baseURL 为 /backend/api/v1', async () => {
const client = createApiClient();
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ code: 200, message: 'success', data: { test: true } }),
});
await client.get('/test');
expect(mockFetch).toHaveBeenCalledWith('/backend/api/v1/test', expect.any(Object));
});
it('开发环境默认 baseURL 为 /api/v1', () => {
expect(resolveApiBaseURL({ MODE: 'development', DEV: true })).toBe('/api/v1');
});
it('测试环境默认 baseURL 为 /backend/api/v1', () => {
expect(resolveApiBaseURL({ MODE: 'test', DEV: false })).toBe('/backend/api/v1');
});
it('生产环境默认 baseURL 为 /backend/api/v1', () => {
expect(resolveApiBaseURL({ MODE: 'production', DEV: false })).toBe('/backend/api/v1');
});
});
describe('VITE_API_BASE_URL 覆盖', () => {
it('使用环境变量覆盖 baseURL', async () => {
const customBaseUrl = 'https://custom.api.com/v2';
const client = createApiClient({ baseUrl: customBaseUrl });
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ code: 200, message: 'success', data: {} }),
});
await client.get('/test');
expect(mockFetch).toHaveBeenCalledWith('https://custom.api.com/v2/test', expect.any(Object));
});
it('环境变量覆盖开发/测试/生产默认值', () => {
expect(
resolveApiBaseURL({
MODE: 'production',
DEV: false,
VITE_API_BASE_URL: 'https://custom.api.com/v2',
})
).toBe('https://custom.api.com/v2');
});
});
describe('响应解包', () => {
it('code === 200 解包成功', async () => {
const client = createApiClient();
const mockData = { id: 1, name: 'test' };
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ code: 200, message: 'success', data: mockData }),
});
const result = await client.get<{ id: number; name: string }>('/test');
expect(result).toEqual(mockData);
});
it('code === 201 解包成功', async () => {
const client = createApiClient();
const mockData = { created: true };
mockFetch.mockResolvedValueOnce({
ok: true,
status: 201,
json: async () => ({ code: 201, message: 'created', data: mockData }),
});
const result = await client.post<{ created: boolean }>('/test', {});
expect(result).toEqual(mockData);
});
});
describe('业务失败', () => {
it('code 非 200/201 抛出 ApiError', async () => {
const client = createApiClient();
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ code: 400, message: 'Bad Request', data: null }),
});
try {
await client.get('/test');
expect.fail('Should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(ApiError);
expect((error as ApiError).code).toBe(400);
expect((error as ApiError).message).toBe('Bad Request');
expect((error as ApiError).isNetworkError).toBe(false);
}
});
it('code === 500 抛出 ApiError', async () => {
const client = createApiClient();
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ code: 500, message: 'Internal Server Error', data: null }),
});
await expect(client.get('/test')).rejects.toThrow(ApiError);
});
});
describe('HTTP 失败', () => {
it('HTTP 404 抛出 ApiError', async () => {
const client = createApiClient();
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
json: async () => ({ code: 404, message: 'Not Found', data: null }),
});
try {
await client.get('/test');
expect.fail('Should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(ApiError);
expect((error as ApiError).code).toBe(404);
expect((error as ApiError).isNetworkError).toBe(false);
}
});
it('HTTP 500 抛出 ApiError', async () => {
const client = createApiClient();
mockFetch.mockResolvedValueOnce({
ok: false,
status: 500,
json: async () => ({ code: 500, message: 'Server Error', data: null }),
});
await expect(client.get('/test')).rejects.toThrow(ApiError);
});
});
describe('网络失败', () => {
it('fetch 抛出网络异常时返回 isNetworkError=true', async () => {
const client = createApiClient();
mockFetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));
await expect(client.get('/test')).rejects.toMatchObject({
isNetworkError: true,
});
});
it('网络异常消息为 "网络连接失败"', async () => {
const client = createApiClient();
mockFetch.mockRejectedValueOnce(new TypeError('Failed to fetch'));
await expect(client.get('/test')).rejects.toMatchObject({
message: '网络连接失败',
});
});
});
});
describe('isSuccessCode 辅助函数', () => {
it('200 是成功码', () => {
expect(isSuccessCode(200)).toBe(true);
});
it('201 是成功码', () => {
expect(isSuccessCode(201)).toBe(true);
});
it('400 不是成功码', () => {
expect(isSuccessCode(400)).toBe(false);
});
it('500 不是成功码', () => {
expect(isSuccessCode(500)).toBe(false);
});
});