Files
SnowLuma/packages/webui/tests/api-client-timeout.test.ts
TanTan fa9c73363d
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run
Publish MCP to npm / Build, test, and publish MCP (push) Waiting to run
Publish SDK to npm / Build, test, and publish SDK (push) Waiting to run
Sync action catalog to docs / sync (push) Waiting to run
Publish UI to npm / Build and publish UI (push) Waiting to run
Build and Release / preflight (push) Waiting to run
SnowLuma v2.4.2 source snapshot
2026-11-13 09:02:00 +08:00

108 lines
3.6 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
const tokenStore = {
load: () => 'test-token',
save: () => undefined,
};
describe('API client request deadline', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
it('aborts a pending request and reports a retryable timeout', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
),
);
const client = createApiClient({ tokenStore });
const request = client.request('/api/processes');
const rejection = expect(request).rejects.toMatchObject({
message: '请求超时,请重试',
code: 'REQUEST_TIMEOUT',
});
await vi.advanceTimersByTimeAsync(30_000);
await rejection;
});
it('cancels a request without preventing a later retry', async () => {
const fetchMock = vi
.fn()
.mockImplementationOnce(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ list: [] }), {
status: 200,
headers: { 'content-type': 'application/json' },
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
const controller = new AbortController();
const cancelled = client.request('/api/processes', { signal: controller.signal });
controller.abort();
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
await expect(
client.request('/api/processes').then((response) => response.json()),
).resolves.toEqual({ list: [] });
});
it('settles a pending login with a retryable timeout message', async () => {
vi.stubGlobal(
'fetch',
vi.fn(
(_url: string, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true },
);
}),
),
);
const client = createApiClient({ tokenStore });
const login = client.login('password');
await vi.advanceTimersByTimeAsync(30_000);
await expect(login).resolves.toEqual({
ok: false,
message: '请求超时,请重试',
});
});
});