168 lines
6.6 KiB
TypeScript
168 lines
6.6 KiB
TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test';
|
|
import { GlobalWindow } from 'happy-dom';
|
|
import { act, createElement } from 'react';
|
|
import type { Root } from 'react-dom/client';
|
|
import { renderToStaticMarkup } from 'react-dom/server';
|
|
import { monitoringReadinessSchema } from '@stock-bot/stock-config/diagnostics';
|
|
import { CacheStatsCard } from '../../apps/stock/web-app/src/features/monitoring/components/CacheStatsCard';
|
|
import { QueueStatsTable } from '../../apps/stock/web-app/src/features/monitoring/components/QueueStatsTable';
|
|
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
|
const previous = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
|
let createRoot: typeof import('react-dom/client').createRoot;
|
|
let Card: typeof import('../../apps/stock/web-app/src/features/monitoring/components/ReadinessCard').ReadinessCard;
|
|
let api: typeof import('../../apps/stock/web-app/src/features/monitoring/services/monitoringApi').monitoringApi;
|
|
let root: Root | undefined, host: HTMLDivElement;
|
|
const requests: { resolve: (response: Response) => void; signal: AbortSignal | undefined }[] = [];
|
|
const snapshot = () =>
|
|
monitoringReadinessSchema.parse({
|
|
observedAt: '2026-10-28T00:00:00.000Z',
|
|
postgres: 'unavailable',
|
|
queue: { connected: false, workers: null, paused: null },
|
|
leases: null,
|
|
orchestrator: null,
|
|
research: { status: 'unavailable', reasons: ['Research PostgreSQL unavailable'] },
|
|
live: 'disabled',
|
|
});
|
|
async function flush(action: () => void = () => {}) {
|
|
await act(async () => {
|
|
action();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
function refresh() {
|
|
const button = host.querySelector('button')!;
|
|
button.click();
|
|
}
|
|
beforeAll(async () => {
|
|
Object.defineProperty(globalThis, 'window', { configurable: true, value: browser });
|
|
Object.defineProperty(globalThis, 'document', { configurable: true, value: browser.document });
|
|
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
|
configurable: true,
|
|
value: true,
|
|
});
|
|
({ createRoot } = await import('react-dom/client'));
|
|
({ ReadinessCard: Card } = await import(
|
|
'../../apps/stock/web-app/src/features/monitoring/components/ReadinessCard'
|
|
));
|
|
({ monitoringApi: api } = await import(
|
|
'../../apps/stock/web-app/src/features/monitoring/services/monitoringApi'
|
|
));
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = 0;
|
|
browser.fetch = ((_input: unknown, init?: RequestInit) =>
|
|
new Promise<Response>(resolve =>
|
|
requests.push({ resolve, signal: init?.signal ?? undefined })
|
|
)) as unknown as typeof browser.fetch;
|
|
const element = browser.document.createElement('div');
|
|
browser.document.body.append(element);
|
|
host = element as unknown as HTMLDivElement;
|
|
root = createRoot(host);
|
|
});
|
|
afterEach(async () => {
|
|
await flush(() => root?.unmount());
|
|
root = undefined;
|
|
host.remove();
|
|
});
|
|
afterAll(() => {
|
|
for (const key of keys) {
|
|
const descriptor = previous.get(key);
|
|
if (descriptor) {Object.defineProperty(globalThis, key, descriptor);}
|
|
else {Reflect.deleteProperty(globalThis, key);}
|
|
}
|
|
browser.happyDOM.abort();
|
|
});
|
|
|
|
test('unknown cache and queue readings never render fabricated zero totals', () => {
|
|
const cache = renderToStaticMarkup(
|
|
createElement(CacheStatsCard, {
|
|
stats: { provider: 'dragonfly', connected: true, stats: { hits: 0, misses: 0, keys: null } },
|
|
})
|
|
);
|
|
expect(cache).toContain('Unknown');
|
|
expect(cache).not.toContain('0.0%');
|
|
const queues = renderToStaticMarkup(
|
|
createElement(QueueStatsTable, {
|
|
queues: [
|
|
{
|
|
name: 'research',
|
|
service: 'orchestrator',
|
|
queue: 'research',
|
|
connected: false,
|
|
jobs: null,
|
|
},
|
|
],
|
|
})
|
|
);
|
|
expect(queues).toContain('Unknown');
|
|
expect(queues).toContain('queue unavailable');
|
|
expect(queues).not.toContain('>Total<');
|
|
const zero = renderToStaticMarkup(
|
|
createElement(QueueStatsTable, {
|
|
queues: [
|
|
{
|
|
name: 'research',
|
|
service: 'orchestrator',
|
|
queue: 'research',
|
|
connected: true,
|
|
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
|
|
workers: { count: 0 },
|
|
},
|
|
],
|
|
})
|
|
);
|
|
expect(zero).toContain('>0<');
|
|
expect(zero).toContain('Unknown');
|
|
});
|
|
|
|
test('readiness loading, unavailable, error and retry states keep older success out of the current snapshot', async () => {
|
|
await flush(() => root!.render(createElement(Card)));
|
|
expect(host.textContent).toContain('Checking readiness');
|
|
await flush(() => requests[0]!.resolve(Response.json(snapshot())));
|
|
expect(host.textContent).toContain('Workers: Unknown');
|
|
expect(host.textContent).toContain('Research PostgreSQL unavailable');
|
|
expect(host.textContent).toContain('Live trading: disabled');
|
|
await flush(refresh);
|
|
expect(host.textContent).not.toContain('Observed:');
|
|
await flush(() => requests[1]!.resolve(Response.json({ error: 'offline' }, { status: 503 })));
|
|
expect(host.textContent).toContain('Readiness diagnostics unavailable');
|
|
await flush(refresh);
|
|
await flush(() => requests[2]!.resolve(Response.json(snapshot())));
|
|
expect(host.textContent).toContain('Observed:');
|
|
expect(host.textContent).not.toContain('Readiness diagnostics unavailable');
|
|
});
|
|
|
|
test('unmounted requests are aborted and cannot replace a new view', async () => {
|
|
await flush(() => root!.render(createElement(Card)));
|
|
const first = requests[0]!;
|
|
await flush(() => root!.render(createElement('div', {}, 'Different view')));
|
|
expect(first.signal?.aborted).toBe(true);
|
|
await flush(() => first.resolve(Response.json(snapshot())));
|
|
expect(host.textContent).toBe('Different view');
|
|
});
|
|
|
|
test('malformed readiness fails closed; structured degraded health remains inspectable', async () => {
|
|
const bad = api.getReadiness();
|
|
requests[0]!.resolve(Response.json({ status: 'healthy' }));
|
|
await expect(bad).rejects.toThrow();
|
|
const health = api.getSystemHealth();
|
|
requests[1]!.resolve(
|
|
Response.json(
|
|
{
|
|
status: 'degraded',
|
|
timestamp: '2026-10-28T00:00:00.000Z',
|
|
uptime: 0,
|
|
memory: { used: 0, total: 1, percentage: 0 },
|
|
services: { cache: {}, queues: [], databases: [] },
|
|
errors: ['Database unavailable'],
|
|
},
|
|
{ status: 503 }
|
|
)
|
|
);
|
|
expect((await health).status).toBe('degraded');
|
|
const unavailable = api.getSystemHealth();
|
|
requests[2]!.resolve(Response.json({ error: 'offline' }, { status: 503 }));
|
|
await expect(unavailable).rejects.toThrow('System health unavailable');
|
|
});
|