Files
weiguang-jewelry-ledger/新账系统/web/test/api.test.ts
T

158 lines
8.0 KiB
TypeScript

// 请求客户端约定:与旧界面 test/request-retry.test.js 相同的重试、恢复与账号切换行为。
import { describe, expect, it } from 'vitest';
import { LedgerClient, retryableMutation, type ClientEnv } from '../src/lib/api';
const ok = (value: unknown) =>
new Response(JSON.stringify(value), { status: 200, headers: { 'Content-Type': 'application/json' } });
const httpError = (status: number, error: string, extra = {}) =>
new Response(JSON.stringify({ error, ...extra }), { status, headers: { 'Content-Type': 'application/json' } });
function harness(fetcher: (url: string, init: RequestInit, attempt: number) => Promise<Response> | Response) {
const saved = new Map<string, string>(),
calls: (RequestInit & { url: string })[] = [],
delays: number[] = [];
let id = 0;
const env: ClientEnv = {
fetch: async (url, init) => {
calls.push({ url, ...init });
return fetcher(url, init, calls.length);
},
storage: {
getItem: k => saved.get(k) ?? null,
setItem: (k, v) => void saved.set(k, String(v)),
removeItem: k => void saved.delete(k),
},
setTimeout: (fn, ms) => {
if (ms === 25000) return 0;
delays.push(ms);
return setTimeout(fn, 0);
},
clearTimeout: () => {},
randomUUID: () => 'operation-key-' + String(++id).padStart(8, '0'),
};
const client = new LedgerClient(env);
client.setUser('user-1');
const headers = (i: number) => calls[i].headers as Record<string, string>;
return { client, env, saved, calls, delays, headers, key: 'mm-pending-user-1' };
}
describe('读请求', () => {
it('502/503/504 与网络中断按 400ms、1200ms 最多重试 2 次,并带 X-Ledger-User', async () => {
const h = harness((_url, _init, attempt) => (attempt === 1 ? new Response('<html>网关</html>', { status: 502 }) : ok({ ready: true })));
await expect(h.client.api('/api/state')).resolves.toEqual({ ready: true });
expect(h.calls).toHaveLength(2);
expect(h.delays).toEqual([400]);
expect(h.headers(0)['X-Ledger-User']).toBe('user-1');
const down = harness(() => {
throw new TypeError('Failed to fetch');
});
await expect(down.client.api('/api/state')).rejects.toThrow('Failed to fetch');
expect(down.calls).toHaveLength(3);
expect(down.delays).toEqual([400, 1200]);
});
it('使用中的账本收到营业时间拒绝立即退回登录页,登录表单本身显示错误', async () => {
const h = harness(() => httpError(403, '非营业时间', { code: 'BUSINESS_HOURS' }));
let locked = 0;
h.env.onBusinessHoursDenied = () => { locked++; };
await expect(h.client.api('/api/login', { member: 'assistant', password: '合成密码' })).rejects.toMatchObject({
status: 403, loginDiagnostic: { method: 'POST', path: '/api/login', status: 403 },
});
expect(locked).toBe(0);
await expect(h.client.api('/api/session')).rejects.toMatchObject({ code: 'BUSINESS_HOURS' });
await expect(h.client.api('/api/stock', { revision: 1 })).rejects.toMatchObject({ code: 'BUSINESS_HOURS' });
expect(locked).toBe(2);
});
it('明确业务拒绝不重试,保留服务端文字;登录类接口不带 X-Ledger-User', async () => {
for (const status of [400, 401, 403, 404, 409, 500]) {
const h = harness(() => httpError(status, '具体业务错误'));
await expect(h.client.api('/api/state')).rejects.toMatchObject({ status, message: '具体业务错误', confirmed: true });
expect(h.calls).toHaveLength(1);
}
const h = harness(url => ok({ user: url === '/api/login' ? { id: 'owner' } : null }));
await h.client.api('/api/session');
await h.client.api('/api/login', { member: 'owner', password: 'x' });
expect(h.headers(0)['X-Ledger-User']).toBeUndefined();
expect(h.headers(1)['X-Ledger-User']).toBeUndefined();
expect(h.headers(1)['Idempotency-Key']).toBeUndefined();
expect(h.headers(1)['X-Requested-With']).toBe('maimai-ledger');
expect(h.headers(1)['Content-Type']).toBe('application/json');
});
});
describe('写入 mutate', () => {
it('白名单写入断线后用同一操作号、同一请求体自动确认,最多 2 次;成功后清除待恢复', async () => {
const h = harness((_url, _init, attempt) => {
if (attempt === 1) throw new TypeError('响应丢失');
return ok({ id: 'order-1' });
});
const data = { customer: '甲', lines: [] as unknown[] };
const saving = h.client.mutate('/api/orders/issue', data);
expect(h.client.busy).toBe(true);
await expect(h.client.mutate('/api/orders/issue', data)).rejects.toThrow('正在保存');
data.customer = '改过';
await expect(saving).resolves.toEqual({ id: 'order-1' });
expect(h.calls).toHaveLength(2);
expect(h.calls[0].body).toBe(h.calls[1].body);
expect(JSON.parse(String(h.calls[1].body)).customer).toBe('甲');
expect(h.headers(0)['Idempotency-Key']).toBe(h.headers(1)['Idempotency-Key']);
expect(h.headers(0)['X-Ledger-User']).toBe('user-1');
expect(h.saved.size).toBe(0);
expect(h.client.busy).toBe(false);
});
it('非白名单写入不自动重试', async () => {
expect(retryableMutation('/api/orders/issue')).toBe(true);
expect(retryableMutation('/api/password')).toBe(false);
const h = harness(() => {
throw new TypeError('断线');
});
await expect(h.client.mutate('/api/password', { value: 1 })).rejects.toThrow();
expect(h.calls).toHaveLength(1);
});
it('自动确认用尽保留待恢复;“恢复原操作”原样重发同一请求与操作号', async () => {
let connected = false;
const h = harness(() => {
if (!connected) throw new TypeError('断线');
return ok({ id: 'order-9' });
});
await expect(h.client.mutate('/api/orders/issue', { customer: '乙' })).rejects.toThrow(/提交结果待确认/);
expect(h.calls).toHaveLength(3);
const job = JSON.parse(h.saved.get(h.key)!);
expect(job).toMatchObject({ url: '/api/orders/issue', userId: 'user-1' });
await expect(h.client.mutate('/api/orders/issue', { customer: '丙' })).rejects.toThrow('恢复原操作');
connected = true;
const recovered = await h.client.retryPending();
expect(recovered?.result).toEqual({ id: 'order-9' });
expect(h.calls).toHaveLength(4);
expect(h.headers(3)['Idempotency-Key']).toBe(job.key);
expect(h.calls[3].body).toBe(h.calls[0].body);
expect(h.saved.size).toBe(0);
});
it('已确认的 400/403/404/409/413 清除待恢复;HTML 拒绝保留待恢复', async () => {
for (const status of [400, 403, 404, 409, 413]) {
const h = harness(() => httpError(status, '请核对'));
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ status, message: '请核对' });
expect(h.saved.size).toBe(0);
}
const h = harness(() => new Response('<html>拒绝</html>', { status: 403 }));
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toThrow(/403.*仍待确认/);
expect(h.saved.has(h.key)).toBe(true);
});
it('服务端 409 ACCOUNT_CHANGED 不清除待恢复、保留原提示;本页账号在退避期间变化立即停止', async () => {
const h = harness(() => httpError(409, '登录账号已在其他页面切换,请刷新后继续;原操作已暂停。', { code: 'ACCOUNT_CHANGED' }));
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ code: 'ACCOUNT_CHANGED', status: 409 });
expect(h.saved.has(h.key)).toBe(true);
const s = harness(() => {
s.client.setUser('user-2');
throw new TypeError('断线');
});
await expect(s.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ code: 'ACCOUNT_CHANGED' });
expect(s.calls).toHaveLength(1);
expect(s.saved.has('mm-pending-user-1')).toBe(true);
expect(s.saved.has('mm-pending-user-2')).toBe(false);
});
it('401 改为提示重新登录后恢复', async () => {
const h = harness(() => httpError(401, '请先登录'));
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toThrow('登录已过期,请刷新并登录,再恢复原操作。');
});
});