nomadro/tests/runtime-transport.test.mjs

104 lines
4.7 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import ts from 'typescript';
// Exercise the real TS transports without a browser, bundler or live service.
async function loadTs(path) {
const source = (await readFile(new URL(path, import.meta.url), 'utf8'))
.replaceAll('import.meta.env.VITE_API_BASE', "''");
const { outputText } = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
});
return import(`data:text/javascript;base64,${Buffer.from(outputText).toString('base64')}`);
}
const portal = await loadTs('../src/lib/client-request.ts');
const admin = await loadTs('../apps/com/admin/src/api/client.ts');
const { serviceUpstream } = await loadTs('../src/lib/online-upstream.ts');
const remoteConfig = await loadTs('../src/lib/remote-config-client.ts');
test('development config and live endpoints use the online backend', () => {
const previousMode = process.env.NODE_ENV;
const previousUrl = process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
try {
delete process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
process.env.NODE_ENV = 'development';
assert.equal(remoteConfig.remoteConfigUrl(), 'https://nomadro.com/api/config');
assert.equal(remoteConfig.remoteConfigStreamUrl(), 'https://nomadro.com/api/config/stream');
assert.equal(remoteConfig.remoteConfigMetaUrl(), 'https://nomadro.com/api/config/meta');
process.env.NODE_ENV = 'production';
assert.equal(remoteConfig.remoteConfigUrl(), '/api/config');
process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL = 'https://example.invalid/api/config';
assert.equal(remoteConfig.remoteConfigMetaUrl(), 'https://example.invalid/api/config/meta');
} finally {
if (previousMode === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = previousMode;
if (previousUrl === undefined) delete process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL;
else process.env.NEXT_PUBLIC_REMOTE_CONFIG_URL = previousUrl;
}
});
test('upstream defaults and explicit overrides', () => {
for (const value of [undefined, '', ' ']) assert.equal(serviceUpstream(value), 'https://nomadro.com');
assert.equal(serviceUpstream(' https://nomadro.com/// '), 'https://nomadro.com');
assert.equal(serviceUpstream('http://127.0.0.1:8021/'), 'http://127.0.0.1:8021');
});
test('portal and admin request contracts', async (t) => {
const originalFetch = globalThis.fetch;
const values = new Map();
globalThis.localStorage = {
getItem: key => values.get(key) ?? null,
setItem: (key, value) => values.set(key, value),
removeItem: key => values.delete(key),
};
globalThis.window = { setTimeout, clearTimeout };
t.after(() => {
globalThis.fetch = originalFetch;
delete globalThis.localStorage;
delete globalThis.window;
});
for (const [name, request] of [['portal', portal.requestJson], ['admin', admin.api]]) {
await t.test(`${name}: no-content responses`, async () => {
for (const status of [204, 205]) {
globalThis.fetch = async () => new Response(null, { status });
await request('/test');
}
});
await t.test(`${name}: FormData keeps browser multipart boundary`, async () => {
globalThis.fetch = async (_url, init) => {
assert.equal(init.headers.has('Content-Type'), false);
return Response.json({ ok: true });
};
await request('/test', { method: 'POST', body: new FormData() });
});
await t.test(`${name}: malformed and null errors stay understandable`, async () => {
for (const body of ['null', '{"detail":[null, {"msg":"bad field"}]}', '<html>bad gateway</html>']) {
globalThis.fetch = async () => new Response(body, { status: 502, headers: { 'Content-Type': 'application/json' } });
await assert.rejects(request('/test'), error => error instanceof Error && !(error instanceof TypeError));
}
});
await t.test(`${name}: cancellation stays cancellation`, async () => {
const controller = new AbortController();
const reason = new DOMException('Navigation cancelled', 'AbortError');
globalThis.fetch = async (_url, init) => {
controller.abort(reason);
throw init.signal.reason;
};
await assert.rejects(request('/test', { signal: controller.signal }), error => error === reason);
});
}
await t.test('stale 401 cannot log out a newer admin session', async () => {
admin.setToken('old');
globalThis.fetch = async () => {
admin.setToken('new');
return Response.json({ detail: 'expired' }, { status: 401 });
};
await assert.rejects(admin.api('/test'), /expired/);
assert.equal(admin.getToken(), 'new');
});
});