Files
ftb-project-management/apps/web/lib/api.test.ts
2026-07-06 18:07:55 +08:00

77 lines
2.6 KiB
TypeScript

import assert from 'node:assert/strict';
import test from 'node:test';
import { __resetApiAvailabilityForTests, api, resolveApiBase } from './api';
test('API base defaults to same-origin in production and localhost in development', () => {
assert.equal(resolveApiBase({ NODE_ENV: 'production' }), '/api/v1');
assert.equal(resolveApiBase({ NODE_ENV: 'development' }), 'http://localhost:3001/api/v1');
assert.equal(
resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: 'https://api.example.com/api/v1/' }),
'https://api.example.com/api/v1',
);
});
test('API base ignores local-only absolute URLs in production', () => {
for (const localApiUrl of [
'http://localhost:3001/api/v1',
'http://127.0.0.1:3001/api/v1',
'http://0.0.0.0:3001/api/v1',
]) {
assert.equal(
resolveApiBase({ NODE_ENV: 'production', NEXT_PUBLIC_API_URL: localApiUrl }),
'/api/v1',
);
}
});
test('API requests use the resolved base path', async () => {
const originalFetch = globalThis.fetch;
const apiBase = resolveApiBase();
const urls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
urls.push(String(input));
return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as typeof fetch;
try {
__resetApiAvailabilityForTests();
await api.post('/config/ai/test', { id: 'provider-1' });
assert.deepEqual(urls, [`${apiBase}/config/ai`, `${apiBase}/config/ai/test`]);
} finally {
globalThis.fetch = originalFetch;
}
});
test('API availability probe retries after a transient failure', async () => {
const originalFetch = globalThis.fetch;
const apiBase = resolveApiBase();
const calls: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
calls.push(String(input));
if (calls.length === 1) throw new Error('temporary network failure');
return new Response(JSON.stringify(init?.method === 'POST' ? { ok: true } : {}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as typeof fetch;
try {
__resetApiAvailabilityForTests();
await assert.rejects(() => api.post('/config/ai/test', { id: 'provider-1' }), /API 不可用/);
await api.post('/config/ai/test', { id: 'provider-1' });
assert.deepEqual(calls, [
`${apiBase}/config/ai`,
`${apiBase}/config/ai`,
`${apiBase}/config/ai/test`,
]);
} finally {
globalThis.fetch = originalFetch;
}
});