request.test.mjs
24.7 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/**
* @file 统一 Request 门面的钉值测试:验证「抹平」三件事——
* 1. 平台差异:注入 sender 时零配置可跑;transport=auto 在假 wx/fetch 环境自动探测;
* 2. 签名差异:内置预设(none/sha1/gsc-hmac) 与注入 signBody 都能挂上;
* 3. 拦截器:业务码归一/成功剔包/登出/错误提示全内置,外部只配 errorHandler / interceptors。
* 另测:Defaults.merge、get/post 别名、returnAll、resolveOnOther、duplicatePrevention、retry、
* 子路径入口 '@uj/api-core/Request' 默认导出。全程假 sender,不依赖真机 wx / 网络。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const core = require('../dist/index.cjs');
const { Request, createRequest, Defaults, RequestError } = core;
const pkg = require('../package.json');
const okBody = { code: '0', message: 'ok', data: { id: 7 } };
/** 假 sender:记录每次 RawRequest,按 handler 决定返回或抛错。 */
function makeSender(handler = () => ({ status: 200, data: okBody })) {
const calls = [];
return {
calls,
sender: {
async send(req) {
calls.push(req);
return handler(req, calls.length);
},
},
};
}
// ---------------------------------------------------------------------------
// 1. 最简调用 / 平台
// ---------------------------------------------------------------------------
test('RQ-BASIC-001 最简调用:new Request({ sender }).post(url) 直接拿到解包后的 data', async () => {
const { calls, sender } = makeSender();
const request = new Request({ sender });
const data = await request.post('/users', { name: 'a' });
assert.deepEqual(data, { id: 7 });
assert.equal(calls.length, 1);
assert.equal(calls[0].url, '/users');
assert.equal(calls[0].method, 'POST');
assert.deepEqual(calls[0].data, { name: 'a' });
});
test('RQ-BASIC-002 零配置不崩:无 baseURL/无签名/普通 JSON 响应原样返回(无 codeKey)', async () => {
const { sender } = makeSender(() => ({ status: 200, data: { hello: 'world' } }));
const data = await new Request({ sender }).get('https://api.example.com/x');
assert.deepEqual(data, { hello: 'world' });
});
test('RQ-PLATFORM-003 transport=auto 在假 wx 环境自动走 wx.request(外部不感知平台)', async () => {
const original = globalThis.wx;
let seen;
globalThis.wx = {
request(opts) {
seen = opts;
opts.success?.({ statusCode: 200, data: okBody });
},
showLoading() {}, hideLoading() {}, showToast() {},
};
try {
const request = new Request({ transport: 'auto', response: { codeKey: 'code' } });
const data = await request.post('/wx-only', { a: 1 });
assert.deepEqual(data, { id: 7 });
assert.equal(seen.url, '/wx-only');
assert.equal(seen.method, 'POST');
} finally {
if (original === undefined) delete globalThis.wx; else globalThis.wx = original;
}
});
test('RQ-PLATFORM-004 transport=fetch 走 fetch(web),transport=host 走主壳注入函数', async () => {
// fetch:用假 globalThis.fetch 拦截,验证 URL / method / body 都过 fetch
const originalFetch = globalThis.fetch;
let fetched;
globalThis.fetch = async (url, init) => {
fetched = { url, init };
return {
status: 200,
headers: { get: () => 'application/json' },
json: async () => okBody,
text: async () => JSON.stringify(okBody),
};
};
try {
const data = await new Request({ transport: 'fetch', response: { codeKey: 'code' } }).get('/v1/ping');
assert.deepEqual(data, { id: 7 });
assert.equal(fetched.url, '/v1/ping');
} finally {
globalThis.fetch = originalFetch;
}
// host:主壳请求函数,验证 data/headers/timeout 透传
let hostReq;
const req = new Request({
transport: 'host',
hostSend: async (r) => {
hostReq = r;
return { status: 200, data: okBody };
},
response: { codeKey: 'code' },
});
await req.post('/host-api', { x: 1 });
assert.equal(hostReq.url, '/host-api');
assert.equal(hostReq.method, 'POST');
assert.deepEqual(hostReq.data, { x: 1 });
});
// ---------------------------------------------------------------------------
// 2. 签名
// ---------------------------------------------------------------------------
test('RQ-SIGN-005 内置 sha1 预设:请求体带 sign + 系统常量 method/v/format/locale/source/appKey', async () => {
const { calls, sender } = makeSender();
const request = new Request({
sender,
profile: 'rop',
hosts: { scrm: 'https://scrm.test' },
pathEnum: { shopmall: '/rop-scrm-shopmall/' },
sign: 'sha1',
appKey: 'k', appSecret: 's',
response: { codeKey: 'code' },
});
await request.post('scrm.api.shopmall.x', { biz: 'v' });
const req = calls[0];
assert.equal(req.url, 'https://scrm.test/rop-scrm-shopmall/router?method=scrm.api.shopmall.x');
assert.equal(req.data.method, 'scrm.api.shopmall.x');
assert.equal(req.data.v, '1.0.0');
assert.equal(req.data.format, 'json');
assert.equal(req.data.locale, 'zh_CN');
assert.equal(req.data.source, 'dj-wechat');
assert.equal(req.data.appKey, 'k');
assert.equal(req.data.biz, 'v');
assert.match(String(req.data.sign), /^[0-9A-F]+$/);
});
test('RQ-SIGN-006 注入 signBody(复用各 app qs 版签名):完全替代内置算法', async () => {
const { calls, sender } = makeSender();
const request = new Request({
sender,
profile: 'rop',
hosts: { scrm: 'https://scrm.test' },
defaultPath: '/rop-scrm-x/',
signBody: async (params, secret) => ({ ...params, custom: secret, sign: 'FROM-APP' }),
appSecret: 'SECRET',
response: { codeKey: 'code' },
});
await request.post('scrm.api.x.y', { a: 1 });
assert.equal(calls[0].data.sign, 'FROM-APP');
assert.equal(calls[0].data.custom, 'SECRET');
});
test('RQ-SIGN-007 gsc profile:HMAC 头部签名产出 X-App-Id/X-Nonce/X-Timestamp/X-Sign,参数进 query', async () => {
const { calls, sender } = makeSender();
const request = new Request({
sender,
profile: 'gsc',
baseURL: 'https://gsc.test/facade',
appKey: 'Mini_App', appSecret: 'sec',
sign: 'gsc-hmac',
response: { codeKey: 'code' },
});
await request.get('/users', { params: { page: 1 } });
const req = calls[0];
assert.match(req.url, /^https:\/\/gsc\.test\/facade\/users\?/);
assert.match(req.url, /page=1/);
assert.equal(req.headers['X-App-Id'], 'Mini_App');
assert.ok(req.headers['X-Nonce']);
assert.ok(req.headers['X-Timestamp']);
assert.match(String(req.headers['X-Sign']), /^[0-9a-f]+$/);
});
test('RQ-SIGN-008 sign=none:不产生任何加签字段', async () => {
const { calls, sender } = makeSender();
await new Request({ sender, profile: 'rop', hosts: { scrm: 'https://s.test' }, defaultPath: '/rop-scrm-x/', sign: 'none' })
.post('scrm.api.x.y', { a: 1 });
assert.equal(calls[0].data.sign, undefined);
});
// ---------------------------------------------------------------------------
// 3. 内置拦截器
// ---------------------------------------------------------------------------
test('RQ-INTERCEPT-009 业务码内置:成功剔包 / 失败抛错+toast / 登出触发回调', async () => {
const toasts = [];
const ui = { toast: (m) => toasts.push(m), showLoading() {}, hideLoading() {} };
const okReq = new Request({ sender: makeSender().sender, response: { codeKey: 'code' }, ui });
assert.deepEqual(await okReq.post('/a'), { id: 7 });
const errReq = new Request({
sender: makeSender(() => ({ status: 200, data: { code: '500', message: '参数错误', data: null } })).sender,
response: { codeKey: 'code' }, ui,
});
await assert.rejects(() => errReq.post('/b'), /参数错误/);
assert.deepEqual(toasts, ['参数错误']);
const logouts = [];
const logoutReq = new Request({
sender: makeSender(() => ({ status: 200, data: { code: 21, message: '登录失效', data: null } })).sender,
response: { codeKey: 'code' }, ui,
onLoginRequired: (code) => logouts.push(code),
});
await assert.rejects(() => logoutReq.post('/c'), /登录失效/);
assert.deepEqual(logouts, [21]);
});
test('RQ-INTERCEPT-010 errorHandler 定制「抛异常之后」:外部接管并决定 resolve 值', async () => {
const seen = [];
const request = new Request({
sender: makeSender(() => ({ status: 200, data: { code: '500', message: '失败啦', data: null } })).sender,
response: { codeKey: 'code' },
ui: { toast() {}, showLoading() {}, hideLoading() {} },
errorHandler: (err) => {
seen.push(err.message);
return { fallback: true };
},
});
const data = await request.post('/x');
assert.deepEqual(data, { fallback: true });
assert.deepEqual(seen, ['失败啦']);
});
test('RQ-INTERCEPT-011 errorHandler 内再抛错则继续 reject', async () => {
const request = new Request({
sender: makeSender(() => ({ status: 200, data: { code: '500', message: 'bad', data: null } })).sender,
response: { codeKey: 'code' },
ui: { toast() {}, showLoading() {}, hideLoading() {} },
errorHandler: () => { throw new Error('handled-elsewhere'); },
});
await assert.rejects(() => request.post('/x'), /handled-elsewhere/);
});
test('RQ-INTERCEPT-012 axios 式 interceptors:request 先改写配置,response 再改写结果', async () => {
const { calls, sender } = makeSender();
const order = [];
const request = new Request({ sender, response: { codeKey: 'code' } });
request.interceptors.request.use((cfg) => {
order.push('req');
return { ...cfg, headers: { ...(cfg.headers ?? {}), 'X-Trace': 't-1' } };
});
request.interceptors.response.use((data) => {
order.push('res');
return { ...data, wrapped: true };
});
const data = await request.post('/x', { a: 1 });
assert.deepEqual(order, ['req', 'res']);
assert.equal(data.wrapped, true);
assert.equal(calls[0].headers['X-Trace'], 't-1');
});
test('RQ-INTERCEPT-013 throwOnError=false / returnAll / resolveOnOther / silent', async () => {
const errBody = { code: '100', message: '提示', data: { keep: 1 } };
const mk = (extra) => new Request({
sender: makeSender(() => ({ status: 200, data: errBody })).sender,
response: { codeKey: 'code', ...extra },
ui: { toast() {}, showLoading() {}, hideLoading() {} },
});
assert.deepEqual(await mk({ throwOnError: false }).post('/a'), errBody);
assert.deepEqual(await mk({ returnAll: true }).post('/b'), errBody);
const toasts = [];
const other = new Request({
sender: makeSender(() => ({ status: 200, data: errBody })).sender,
response: { codeKey: 'code', resolveOnOther: true, toastOnOtherCodes: ['100'] },
ui: { toast: (m) => toasts.push(m), showLoading() {}, hideLoading() {} },
});
assert.deepEqual(await other.post('/c'), { keep: 1 });
assert.deepEqual(toasts, ['提示']);
await other.post('/d', undefined, { silent: true });
assert.equal(toasts.length, 1); // silent 抑制 -1/其它码 toast
});
test('RQ-INTERCEPT-014 事件回调:request/response/success/error/complete 全链路', async () => {
const fired = [];
const request = new Request({
sender: makeSender().sender,
response: { codeKey: 'code' },
events: {
request: () => fired.push('request'),
response: () => fired.push('response'),
success: () => fired.push('success'),
complete: () => fired.push('complete'),
},
});
await request.post('/x');
assert.deepEqual(fired.sort(), ['complete', 'request', 'response', 'success']);
});
// ---------------------------------------------------------------------------
// 4. 配置合并 / 别名 / 高级
// ---------------------------------------------------------------------------
test('RQ-CONFIG-015 Defaults.merge:默认值 + 单次覆盖,headers/response 做浅合并', async () => {
const { calls, sender } = makeSender();
const d = new Defaults({ headers: { A: '1', B: '2' }, response: { codeKey: 'code', dataKey: 'data' } });
const merged = d.merge({ headers: { B: '9' }, response: { returnAll: true } });
assert.deepEqual(merged.headers, { A: '1', B: '9' });
assert.equal(merged.response.codeKey, 'code');
assert.equal(merged.response.returnAll, true);
const request = new Request({ sender, headers: { A: '1' }, response: { codeKey: 'code' } });
await request.post('/x', undefined, { headers: { B: '2' } });
assert.equal(calls[0].headers.A, '1');
assert.equal(calls[0].headers.B, '2');
});
test('RQ-CONFIG-016 get/post/put/patch/delete 别名都指向同一 pipeline', async () => {
const { calls, sender } = makeSender();
const request = new Request({ sender, response: { codeKey: 'code' } });
await request.get('/a');
await request.post('/b', { x: 1 });
await request.put('/c', { x: 2 });
await request.patch('/d', { x: 3 });
await request.delete('/e');
assert.deepEqual(calls.map((c) => c.method), ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
});
test('RQ-CONFIG-017 createRequest 工厂 == new Request;子路径 `@uj/api-core/Request` 别名到同一 bundle', async () => {
assert.equal(typeof createRequest, 'function');
assert.ok(createRequest() instanceof Request);
assert.ok(new RequestError('x') instanceof Error);
// 主入口需有 default 导出,子路径才能 `import Request from '@uj/api-core/Request'`
assert.equal(core.default, Request);
// 子路径别名到同一产物(不是独立 entry,避免出现第二份 Request 类)
assert.equal(pkg.exports['./Request'].require, './dist/index.cjs');
assert.equal(pkg.exports['./Request'].import, './dist/index.js');
assert.equal(pkg.exports['./Request'].types, './dist/index.d.ts');
});
test('RQ-ADV-018 beforeRequest 前置拦截:abort 直接返回 value,不发请求', async () => {
const { calls, sender } = makeSender();
const request = new Request({ sender, beforeRequest: () => ({ abort: true, value: 'offline' }) });
assert.equal(await request.post('/x'), 'offline');
assert.equal(calls.length, 0);
});
test('RQ-ADV-019 duplicatePrevention:进行中重复调用直接 reject', async () => {
let release;
const { sender } = makeSender(() => new Promise((r) => { release = () => r({ status: 200, data: okBody }); }));
const request = new Request({ sender, duplicatePrevention: true, response: { codeKey: 'code' } });
const p1 = request.post('/same');
await assert.rejects(() => request.post('/same'), /请勿重复提交/);
release();
await p1;
});
test('RQ-ADV-020 retry:传输层失败按次数重试后成功', async () => {
let n = 0;
const { sender } = makeSender(() => {
n++;
if (n < 3) throw new Error('network');
return { status: 200, data: okBody };
});
const request = new Request({ sender, retry: 2, response: { codeKey: 'code' }, ui: { toast() {}, showLoading() {}, hideLoading() {} } });
assert.deepEqual(await request.post('/x'), { id: 7 });
assert.equal(n, 3);
});
test('RQ-SESSION-021 异步 sessionId 统一注入(三个 profile 抹平),rop 进签名体、gsc/plain 进 query', async () => {
const { calls, sender } = makeSender();
const rop = new Request({
sender, profile: 'rop', hosts: { scrm: 'https://s.test' }, defaultPath: '/rop-scrm-x/',
sign: 'none', session: { sessionId: async () => 'sess-9' }, response: { codeKey: 'code' },
});
await rop.post('scrm.api.x.y', { a: 1 });
assert.equal(calls[0].data.sessionId, 'sess-9');
const plain = new Request({ sender, session: { sessionId: () => 'sess-9' }, response: { codeKey: 'code' } });
await plain.get('/x');
assert.match(calls[1].url, /sessionId=sess-9/);
});
// ---------------------------------------------------------------------------
// 4. web 主壳:normalize 透传 + 已归一信封自动解包
// ---------------------------------------------------------------------------
test('RQ-HOST-022 transport=host:normalize 挂到 transformResponse,且 post(url) 直接拿到业务数据', async () => {
// 与 web points 的 normalizeGlsxEnvelope 同形:原始字符串 → { data } / { code, message }
const normalizeLegacy = (raw) => {
const body = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (body && body.code === '0') return { data: body.data };
return { code: 500, message: body?.message || '接口返回失败' };
};
let hostReq;
const request = new Request({
transport: 'host',
normalize: normalizeLegacy,
hostSend: async (r) => {
hostReq = r;
// 模拟主壳 axios:transformResponse 在响应拦截器之前执行
const rawText = JSON.stringify({ code: '0', message: 'ok', data: { id: 7 } });
const body = r.transformResponse?.[0]?.(rawText, {}) ?? JSON.parse(rawText);
return { status: 200, data: body };
},
});
const data = await request.post('/legacy/router?method=x', { a: 1 });
assert.deepEqual(data, { id: 7 });
assert.equal(hostReq.url, '/legacy/router?method=x');
assert.equal(hostReq.method, 'POST');
assert.equal(hostReq.transformResponse.length, 1);
assert.deepEqual(
hostReq.transformResponse[0](JSON.stringify({ code: '0', data: { id: 7 } }), {}),
{ data: { id: 7 } },
);
});
test('RQ-HOST-023 三种 profile 均把 normalize 透传给 sender;已归一信封在 wx/fetch 下也能解包', async () => {
const { calls, sender } = makeSender((req) => ({
status: 200,
// 模拟 wx/uni/fetch sender:收到响应后调用 req.normalize
data: req.normalize ? req.normalize({ code: '0', data: { id: 7 } }) : { code: '0', data: { id: 7 } },
}));
const normalize = (raw) => ({ data: raw.data });
const base = { sender, normalize, sign: 'none' };
await new Request(base).post('/plain');
await new Request({
...base, profile: 'rop', hosts: { scrm: 'https://s.test' }, defaultPath: '/rop-scrm-x/',
}).post('scrm.api.x.y');
await new Request({ ...base, profile: 'gsc', baseURL: 'https://g.test' }).post('/gsc');
assert.equal(calls.length, 3);
for (const call of calls) assert.equal(typeof call.normalize, 'function');
});
test('RQ-HOST-024 contentType:false:不带默认 Content-Type;有请求体时才补 application/json(对齐老 web 拦截器)', async () => {
const hostReqs = [];
const request = new Request({
transport: 'host',
contentType: false,
hostSend: async (r) => {
hostReqs.push(r);
return { status: 200, data: { data: { id: 7 } } };
},
});
// GET 无请求体:不带头,签名 canonical 的 media 为空串(老 web 语义)
await request.get('/list', { params: { a: 1 } });
assert.equal(hostReqs[0].headers['Content-Type'], undefined);
assert.equal(hostReqs[0].headers['content-type'], undefined);
// POST 有请求体:补 application/json(老拦截器在加签之后补,不影响 canonical 的 media)
await request.post('/legacy/router', { method: 'x.y.z' });
assert.equal(hostReqs[1].headers['Content-Type'], 'application/json');
});
test('RQ-HOST-025 web 主壳完整链路:预签名 body 原样 + normalize 挂 transformResponse + errorHandler 还原 code', async () => {
let hostReq;
const hostError = Object.assign(new Error('登录已失效'), { code: 10002 });
const request = new Request({
transport: 'host',
contentType: false,
sign: 'none',
normalize: (raw) => (raw && raw.code === '0' ? { data: raw.data } : { code: 500, message: '失败' }),
hostSend: async (r) => {
hostReq = r;
if (r.data.fail) throw hostError;
return {
status: 200,
data: r.transformResponse[0]({ code: '0', data: { id: 7 } }, {}),
};
},
errorHandler: (err) => {
throw err.cause ?? err;
},
});
const body = { method: 'scrm.api.shopmall.x', appKey: 'k', sign: 'PRE-SIGNED' };
const data = await request.post('/rop-scrm-shopmall/router', body);
assert.deepEqual(data, { id: 7 });
assert.deepEqual(hostReq.data, body);
// 有请求体但未显式指定 Content-Type → 门面补 application/json(老 web 拦截器同款时机:加签之后)。
assert.equal(hostReq.headers['Content-Type'], 'application/json');
assert.equal(hostReq.transformResponse.length, 1);
await assert.rejects(
() => request.post('/rop-scrm-shopmall/router', { ...body, fail: true }),
(err) => err === hostError,
);
});
test('RQ-CONFIG-026 默认 timeout=60s(对齐 wx.request),单次调用可覆盖成 120s 上传档', async () => {
const { calls, sender } = makeSender();
const request = new Request({ sender, response: { codeKey: 'code' } });
await request.post('/normal');
assert.equal(calls[0].timeout, 60000);
await request.post('/upload', { file: 'BASE64' }, { timeout: 120000 });
assert.equal(calls[1].timeout, 120000);
});
// ---------------------------------------------------------------------------
// 7. web 主壳(platform-core/http.ts)依赖的通用能力
// ---------------------------------------------------------------------------
test('RQ-WEB-027 contextPath + 头部签名:path/query/media/body 与线上 URL 同源', async () => {
const { calls, sender } = makeSender(() => ({ status: 200, data: { code: 200, data: {} } }));
let signInput;
const request = new Request({
sender,
baseURL: 'http://api.test:8080',
contextPath: '/youjia',
contentType: false,
sign: { id: 'capture', headers: (input) => { signInput = input; return {}; } },
response: { successCodes: [200], dataMode: 'envelope' },
});
await request.request({
method: 'GET',
url: '/store/listing/page',
params: { pageNum: 1, pageSize: 20, name: 'a b' },
});
assert.equal(signInput.path, '/youjia/store/listing/page');
assert.equal(signInput.query, 'name=a%20b&pageNum=1&pageSize=20');
// GET 无请求体 → media / body 均为空串(老 web 拦截器口径)
assert.equal(signInput.mediaType, '');
assert.equal(signInput.bodyString, '');
assert.equal(calls[0].url, 'http://api.test:8080/youjia/store/listing/page?name=a%20b&pageNum=1&pageSize=20');
// 已自带 context-path 时不再重复拼
await request.request({ method: 'GET', url: '/youjia/system/user/info' });
assert.equal(signInput.path, '/youjia/system/user/info');
assert.equal(calls[1].url, 'http://api.test:8080/youjia/system/user/info');
// 有请求体 → media=application/json,body 与发送体逐字节一致
const body = { account: 'admin', remember: true };
await request.post('/system/auth/login', body);
assert.equal(signInput.mediaType, 'application/json');
assert.equal(signInput.bodyString, JSON.stringify(body));
assert.equal(calls[2].headers['Content-Type'], 'application/json');
});
test('RQ-WEB-028 binaryHeaders:非 JSON 响应返回 { data, headers },JSON 响应照常归一', async () => {
const { sender } = makeSender((req) =>
req.url.includes('/export')
? { status: 200, data: 'FILE', headers: { 'content-type': 'application/vnd.ms-excel', 'content-disposition': 'attachment; filename=a.xlsx' } }
: { status: 200, data: { code: 200, data: { id: 1 } }, headers: { 'content-type': 'application/json' } },
);
const request = new Request({
sender,
response: { successCodes: [200], dataMode: 'envelope', binaryHeaders: true },
});
const file = await request.get('/store/listing/export');
assert.deepEqual(file, {
data: 'FILE',
headers: { 'content-type': 'application/vnd.ms-excel', 'content-disposition': 'attachment; filename=a.xlsx' },
});
const json = await request.get('/store/listing/page');
assert.deepEqual(json, { code: 200, message: undefined, data: { id: 1 } }.code === 200 ? json : null);
assert.equal(json.code, 200);
assert.deepEqual(json.data, { id: 1 });
});
test('RQ-WEB-029 业务失败:异常带 code 与 data;toastOnError:false 时不弹提示', async () => {
const toasts = [];
const { sender } = makeSender(() => ({
status: 200,
data: { code: 500, message: '库存不足', data: { skuId: 9 } },
}));
const request = new Request({
sender,
response: { successCodes: [200], dataMode: 'envelope', toastOnError: false },
ui: { toast: (m) => toasts.push(m) },
});
await assert.rejects(
() => request.post('/store/listing/offline', {}),
(err) => err instanceof RequestError && err.code === 500 && err.message === '库存不足' && err.data.skuId === 9,
);
assert.deepEqual(toasts, []);
});
test('RQ-WEB-030 transformResponse 由门面执行:既能解码 ArrayBuffer,也能读到响应头', async () => {
const bytes = new TextEncoder().encode('{"code":200,"data":{"ok":true}}');
const { sender } = makeSender(() => ({
status: 200,
data: bytes.buffer,
headers: { 'content-type': 'application/json' },
}));
const request = new Request({
sender,
response: { successCodes: [200], dataMode: 'envelope' },
transformResponse: [
(raw, headers) => {
assert.equal(headers['content-type'], 'application/json');
return raw instanceof ArrayBuffer ? new TextDecoder().decode(raw) : raw;
},
],
});
const res = await request.get('/store/listing/export');
assert.equal(res.code, 200);
assert.deepEqual(res.data, { ok: true });
});