BIT-15744: add remaining unit tests for admin-ui, api routes, collector-worker db, ingest-api services

Complete test coverage implementation for errors.bitreport.pt:

admin-ui (98 tests):
- test/components/: AppShell, DataAlert, IncidentNotes, KpiCard, SeverityBadge, StateBadge
- test/lib/: format, demo-incidents, incidents-data, incidents-data-api, stats-data, stats-data-api
- vitest.config.ts with jsdom + v8 coverage + @vitejs/plugin-react

api route tests (54 tests):
- src/routes/admin/auth.test.ts (15 tests)
- src/routes/admin/incidents.test.ts (11 tests)
- src/routes/admin/stats.test.ts (18 tests)
- src/routes/public/errorMonitoringStats.test.ts (10 tests)

collector-worker db/scheduler tests (22 tests):
- src/db/collectorRunWriter.test.ts (10 tests)
- src/db/loadActiveSources.test.ts (6 tests)
- src/scheduler/runHttpSourceOnce.test.ts (6 tests)

ingest-api service tests (13 tests):
- src/buildApp.test.ts, plugins/prometheus.test.ts
- services/ingestAuth.test.ts, services/processIngestBatch.utils.test.ts

Total: 187 additional tests (255 total across all modules). All pass.

Paperclip-Issue: BIT-15744
Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
David SantosandPaperclip committed 2026-05-03 07:24:38 +00:00
1 parent 989a92ba07
commit 3d4444eb21
33 files changed
+6374 -24

No files matched your search

+2164 -19
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -8,7 +8,10 @@
"build": "next build",
"start": "next start -p 3040",
"lint": "next lint",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"bootstrap": "^5.3.3",
@@ -18,13 +21,19 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/node": "^22.9.0",
"@types/react": "19.2.14",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.5",
"eslint": "^9.15.0",
"eslint-config-next": "15.5.15",
"jsdom": "^29.1.0",
"sass": "^1.81.0",
"typescript": "^5.6.3"
"typescript": "^5.6.3",
"vitest": "^4.1.5"
},
"engines": {
"node": ">=20"
@@ -0,0 +1,69 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { AppShell } from '@/components/AppShell';
vi.mock('next/link', () => ({
default: ({ href, children, className }: { href: string; children: React.ReactNode; className?: string }) => (
<a href={href} className={className}>{children}</a>
),
}));
describe('AppShell', () => {
it('renders the page title', () => {
render(<AppShell title="Dashboard"><div>content</div></AppShell>);
expect(screen.getByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
});
it('renders child content', () => {
render(<AppShell title="Test"><p>Hello content</p></AppShell>);
expect(screen.getByText('Hello content')).toBeInTheDocument();
});
it('renders the BitReport brand link', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.getByText('BitReport')).toBeInTheDocument();
});
it('renders nav links for Painel and Incidentes', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.getByRole('link', { name: /Painel/i })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Incidentes/i })).toBeInTheDocument();
});
it('renders breadcrumb when provided', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Home', href: '/' }, { label: 'Current' }]}>
<div />
</AppShell>
);
expect(screen.getByRole('navigation', { name: 'breadcrumb' })).toBeInTheDocument();
expect(screen.getByText('Home')).toBeInTheDocument();
expect(screen.getByText('Current')).toBeInTheDocument();
});
it('does not render breadcrumb nav when breadcrumb is empty', () => {
render(<AppShell title="T" breadcrumb={[]}><div /></AppShell>);
expect(screen.queryByRole('navigation', { name: 'breadcrumb' })).toBeNull();
});
it('does not render breadcrumb nav when breadcrumb is omitted', () => {
render(<AppShell title="T"><div /></AppShell>);
expect(screen.queryByRole('navigation', { name: 'breadcrumb' })).toBeNull();
});
it('breadcrumb item with href renders as a link', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Home', href: '/home' }]}><div /></AppShell>
);
const link = screen.getByText('Home').closest('a');
expect(link).not.toBeNull();
});
it('breadcrumb item without href has aria-current="page"', () => {
render(
<AppShell title="T" breadcrumb={[{ label: 'Current page' }]}><div /></AppShell>
);
const item = screen.getByText('Current page').closest('li');
expect(item?.getAttribute('aria-current')).toBe('page');
});
});
@@ -0,0 +1,41 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { DataAlert } from '@/components/DataAlert';
describe('DataAlert', () => {
it('renders the title', () => {
render(<DataAlert variant="warning" title="Aviso" body="Algo correu mal." />);
expect(screen.getByText('Aviso')).toBeInTheDocument();
});
it('renders the body text', () => {
render(<DataAlert variant="info" title="Info" body="Nenhuma informação disponível." />);
expect(screen.getByText('Nenhuma informação disponível.')).toBeInTheDocument();
});
it('applies the correct alert variant class', () => {
const { container } = render(<DataAlert variant="danger" title="Erro" body="Falha." />);
expect(container.querySelector('.alert-danger')).not.toBeNull();
});
it('applies alert-warning class for warning variant', () => {
const { container } = render(<DataAlert variant="warning" title="X" body="Y" />);
expect(container.querySelector('.alert-warning')).not.toBeNull();
});
it('applies alert-info class for info variant', () => {
const { container } = render(<DataAlert variant="info" title="X" body="Y" />);
expect(container.querySelector('.alert-info')).not.toBeNull();
});
it('has role="status" for accessibility', () => {
render(<DataAlert variant="warning" title="Status" body="OK" />);
expect(screen.getByRole('status')).toBeInTheDocument();
});
it('renders title in a strong element', () => {
render(<DataAlert variant="info" title="My Title" body="body text" />);
const strong = screen.getByText('My Title');
expect(strong.tagName).toBe('STRONG');
});
});
@@ -0,0 +1,51 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { IncidentNotes } from '@/components/IncidentNotes';
describe('IncidentNotes', () => {
beforeEach(() => {
sessionStorage.clear();
});
it('renders the label', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByText('Notas do operador')).toBeInTheDocument();
});
it('renders a textarea', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByRole('textbox')).toBeInTheDocument();
});
it('starts with empty textarea when no stored value', () => {
render(<IncidentNotes incidentId="inc-new" />);
const ta = screen.getByRole('textbox') as HTMLTextAreaElement;
expect(ta.value).toBe('');
});
it('loads stored value from sessionStorage', () => {
sessionStorage.setItem('er-incident-notes:inc-42', 'saved note');
render(<IncidentNotes incidentId="inc-42" />);
const ta = screen.getByRole('textbox') as HTMLTextAreaElement;
expect(ta.value).toBe('saved note');
});
it('saves to sessionStorage when user types', () => {
render(<IncidentNotes incidentId="inc-99" />);
const ta = screen.getByRole('textbox');
fireEvent.change(ta, { target: { value: 'new note text' } });
expect(sessionStorage.getItem('er-incident-notes:inc-99')).toBe('new note text');
});
it('shows the helper text about server persistence', () => {
render(<IncidentNotes incidentId="inc-1" />);
expect(screen.getByText(/não são enviadas ao servidor/i)).toBeInTheDocument();
});
it('textarea is linked to its label via htmlFor/id', () => {
render(<IncidentNotes incidentId="inc-1" />);
const label = screen.getByText('Notas do operador');
const ta = screen.getByRole('textbox');
expect(label.getAttribute('for')).toBe(ta.getAttribute('id'));
});
});
+42
View File
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { KpiCard } from '@/components/KpiCard';
describe('KpiCard', () => {
it('renders the label text', () => {
render(<KpiCard label="Total Errors" value={42} variant="danger" />);
expect(screen.getByText('Total Errors')).toBeInTheDocument();
});
it('renders the numeric value', () => {
render(<KpiCard label="Open Incidents" value={7} variant="primary" />);
expect(screen.getByText('7')).toBeInTheDocument();
});
it('applies the correct border variant class', () => {
const { container } = render(<KpiCard label="Resolved" value={100} variant="success" />);
expect(container.querySelector('.border-success')).not.toBeNull();
});
it('applies the correct text variant class', () => {
render(<KpiCard label="Critical" value={3} variant="dark" />);
const valueEl = screen.getByText('3');
expect(valueEl.className).toContain('text-dark');
});
it('renders value zero', () => {
render(<KpiCard label="No errors" value={0} variant="secondary" />);
expect(screen.getByText('0')).toBeInTheDocument();
});
it('renders large numbers', () => {
render(<KpiCard label="All time" value={99999} variant="warning" />);
expect(screen.getByText('99999')).toBeInTheDocument();
});
it('applies card and col wrapper classes', () => {
const { container } = render(<KpiCard label="test" value={1} variant="primary" />);
expect(container.querySelector('.card')).not.toBeNull();
expect(container.querySelector('.card-body')).not.toBeNull();
});
});
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { SeverityBadge } from '@/components/SeverityBadge';
import type { Severity } from '@/lib/types';
describe('SeverityBadge', () => {
const cases: { severity: Severity; label: string; cssClass: string }[] = [
{ severity: 'critical', label: 'Crítico', cssClass: 'text-bg-dark' },
{ severity: 'high', label: 'Alto', cssClass: 'text-bg-danger' },
{ severity: 'medium', label: 'Médio', cssClass: 'text-bg-warning' },
{ severity: 'low', label: 'Baixo', cssClass: 'text-bg-info' },
{ severity: 'info', label: 'Info', cssClass: 'text-bg-light' },
];
cases.forEach(({ severity, label, cssClass }) => {
it(`renders "${label}" label for severity="${severity}"`, () => {
render(<SeverityBadge severity={severity} />);
expect(screen.getByText(label)).toBeInTheDocument();
});
it(`applies "${cssClass}" class for severity="${severity}"`, () => {
render(<SeverityBadge severity={severity} />);
const badge = screen.getByText(label);
expect(badge.className).toContain(cssClass);
expect(badge.className).toContain('badge');
});
});
it('renders as a span element', () => {
render(<SeverityBadge severity="high" />);
expect(screen.getByText('Alto').tagName).toBe('SPAN');
});
});
@@ -0,0 +1,32 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { StateBadge } from '@/components/StateBadge';
import type { IncidentState } from '@/lib/types';
describe('StateBadge', () => {
const cases: { state: IncidentState; label: string; cssClass: string }[] = [
{ state: 'open', label: 'Aberto', cssClass: 'text-bg-danger' },
{ state: 'investigating', label: 'Em investigação', cssClass: 'text-bg-warning' },
{ state: 'resolved', label: 'Resolvido', cssClass: 'text-bg-success' },
{ state: 'ignored', label: 'Ignorado', cssClass: 'text-bg-secondary' },
];
cases.forEach(({ state, label, cssClass }) => {
it(`renders "${label}" label for state="${state}"`, () => {
render(<StateBadge state={state} />);
expect(screen.getByText(label)).toBeInTheDocument();
});
it(`applies "${cssClass}" class for state="${state}"`, () => {
render(<StateBadge state={state} />);
const badge = screen.getByText(label);
expect(badge.className).toContain(cssClass);
expect(badge.className).toContain('badge');
});
});
it('renders as a span element', () => {
render(<StateBadge state="open" />);
expect(screen.getByText('Aberto').tagName).toBe('SPAN');
});
});
+54
View File
@@ -0,0 +1,54 @@
import { describe, it, expect } from 'vitest';
import { getDemoIncidentSummaries, getDemoIncidentDetail } from '@/lib/demo-incidents';
describe('getDemoIncidentSummaries', () => {
it('returns a non-empty array', () => {
const result = getDemoIncidentSummaries();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
});
it('each summary has required fields', () => {
const summaries = getDemoIncidentSummaries();
for (const s of summaries) {
expect(typeof s.id).toBe('string');
expect(typeof s.projectSlug).toBe('string');
expect(typeof s.fingerprint).toBe('string');
expect(typeof s.title).toBe('string');
expect(['critical', 'high', 'medium', 'low', 'info']).toContain(s.severity);
expect(['open', 'investigating', 'resolved', 'ignored']).toContain(s.currentState);
expect(typeof s.occurrencesCount).toBe('number');
}
});
it('returns a stable list on repeated calls', () => {
const first = getDemoIncidentSummaries();
const second = getDemoIncidentSummaries();
expect(first.length).toBe(second.length);
expect(first[0].id).toBe(second[0].id);
});
});
describe('getDemoIncidentDetail', () => {
it('returns null for unknown id', () => {
expect(getDemoIncidentDetail('nonexistent-id')).toBeNull();
});
it('returns a detail for a known demo id', () => {
const summaries = getDemoIncidentSummaries();
const id = summaries[0].id;
const detail = getDemoIncidentDetail(id);
expect(detail).not.toBeNull();
expect(detail?.id).toBe(id);
});
it('returned detail has occurrences array', () => {
const summaries = getDemoIncidentSummaries();
const detail = getDemoIncidentDetail(summaries[0].id);
expect(Array.isArray(detail?.occurrences)).toBe(true);
});
it('returns null for empty string id', () => {
expect(getDemoIncidentDetail('')).toBeNull();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, it, expect } from 'vitest';
import { formatDateTime } from '@/lib/format';
describe('formatDateTime', () => {
it('formats a valid ISO string', () => {
const result = formatDateTime('2024-01-15T10:30:00Z');
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
expect(result).not.toBe('2024-01-15T10:30:00Z');
});
it('returns the raw string for an invalid date', () => {
expect(formatDateTime('not-a-date')).toBe('not-a-date');
});
it('returns the raw string for an empty string', () => {
expect(formatDateTime('')).toBe('');
});
it('handles date-only ISO strings', () => {
const result = formatDateTime('2024-06-01');
expect(typeof result).toBe('string');
expect(result.length).toBeGreaterThan(0);
});
it('handles ISO strings with milliseconds', () => {
const result = formatDateTime('2024-03-20T14:22:33.456Z');
expect(typeof result).toBe('string');
expect(result).not.toBe('2024-03-20T14:22:33.456Z');
});
it('returns consistent output for the same input', () => {
const iso = '2024-07-04T12:00:00Z';
expect(formatDateTime(iso)).toBe(formatDateTime(iso));
});
});
@@ -0,0 +1,190 @@
/**
* Tests for fetchIncidentList and fetchIncidentDetail covering the API-backed paths.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchIncidentList, fetchIncidentDetail } from '@/lib/incidents-data';
import type { IncidentSummary } from '@/lib/types';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const PREV_API_BASE = process.env.ERROR_REPORTING_ADMIN_API_BASE;
const mockIncident: IncidentSummary = {
id: 'inc-001',
projectSlug: 'wdmi-store',
fingerprint: 'fp-abc',
title: 'Uncaught TypeError',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00Z',
lastSeenAt: '2026-01-02T00:00:00Z',
occurrencesCount: 5,
};
beforeEach(() => {
process.env.ERROR_REPORTING_ADMIN_API_BASE = 'http://test-api.local';
delete process.env.ERROR_REPORTING_UI_DEMO;
});
afterEach(() => {
if (PREV_API_BASE === undefined) {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
} else {
process.env.ERROR_REPORTING_ADMIN_API_BASE = PREV_API_BASE;
}
vi.restoreAllMocks();
});
describe('fetchIncidentList — API mode', () => {
it('returns incidents from API on success', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [mockIncident] }),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incidents).toHaveLength(1);
expect(result.incidents[0].id).toBe('inc-001');
expect(result.source).toBe('api');
}
});
it('passes state/severity/project/q as query params', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [] }),
});
await fetchIncidentList({ state: 'open', severity: 'high', project: 'wdmi', q: 'TypeError' });
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).toContain('state=open');
expect(calledUrl).toContain('severity=high');
expect(calledUrl).toContain('project=wdmi');
expect(calledUrl).toContain('q=TypeError');
});
it('omits empty params from query string', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ incidents: [] }),
});
await fetchIncidentList({});
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).not.toContain('state=');
expect(calledUrl).not.toContain('severity=');
});
it('returns unreachable error when fetch throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('ECONNREFUSED'));
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
expect(result.message).toContain('ECONNREFUSED');
}
});
it('returns unreachable error when API returns non-ok status', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
}
});
it('returns empty incidents array when payload has no incidents field', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incidents).toHaveLength(0);
}
});
});
describe('fetchIncidentDetail — API mode', () => {
const detailPayload = {
incident: {
id: 'inc-001',
projectSlug: 'wdmi-store',
fingerprint: 'fp-abc',
title: 'Uncaught TypeError',
severity: 'high',
currentState: 'open',
firstSeenAt: '2026-01-01T00:00:00Z',
lastSeenAt: '2026-01-02T00:00:00Z',
occurrencesCount: 5,
recentOccurrences: [],
stateHistory: [],
},
};
it('returns incident detail on success', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(detailPayload),
});
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incident.id).toBe('inc-001');
expect(result.source).toBe('api');
}
});
it('returns not_found on 404', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 404,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentDetail('unknown-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_found');
}
});
it('returns unreachable when API throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('timeout'));
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
expect(result.message).toContain('timeout');
}
});
it('returns unreachable on non-404 HTTP error', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 500,
json: () => Promise.resolve({}),
});
const result = await fetchIncidentDetail('inc-001');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('unreachable');
}
});
it('URL-encodes the incident id', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(detailPayload),
});
await fetchIncidentDetail('inc/with/slashes');
const calledUrl = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
expect(calledUrl).toContain('inc%2Fwith%2Fslashes');
});
});
+176
View File
@@ -0,0 +1,176 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { computeKpis, fetchIncidentList, fetchIncidentDetail } from '@/lib/incidents-data';
import { getDemoIncidentSummaries } from '@/lib/demo-incidents';
import type { IncidentSummary } from '@/lib/types';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const makeIncident = (state: IncidentSummary['currentState']): IncidentSummary => ({
id: Math.random().toString(),
projectSlug: 'test',
fingerprint: 'fp',
title: 'Error',
severity: 'high',
currentState: state,
firstSeenAt: '2024-01-01T00:00:00Z',
lastSeenAt: '2024-01-01T00:00:00Z',
occurrencesCount: 1,
});
describe('computeKpis', () => {
it('returns all zeros for empty list', () => {
const result = computeKpis([]);
expect(result).toEqual({ total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 });
});
it('counts total correctly', () => {
const incidents = [makeIncident('open'), makeIncident('resolved'), makeIncident('ignored')];
expect(computeKpis(incidents).total).toBe(3);
});
it('counts each state correctly', () => {
const incidents = [
makeIncident('open'),
makeIncident('open'),
makeIncident('investigating'),
makeIncident('resolved'),
makeIncident('ignored'),
];
const result = computeKpis(incidents);
expect(result.open).toBe(2);
expect(result.investigating).toBe(1);
expect(result.resolved).toBe(1);
expect(result.ignored).toBe(1);
expect(result.total).toBe(5);
});
it('handles all incidents in a single state', () => {
const incidents = [makeIncident('resolved'), makeIncident('resolved')];
const result = computeKpis(incidents);
expect(result.resolved).toBe(2);
expect(result.open).toBe(0);
});
});
describe('fetchIncidentList — not_configured', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns not_configured when API base is missing and demo is off', async () => {
const result = await fetchIncidentList({});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_configured');
}
});
});
describe('fetchIncidentList — demo mode', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
process.env.ERROR_REPORTING_UI_DEMO = '1';
});
afterEach(() => {
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns demo incidents when no API base is set', async () => {
const result = await fetchIncidentList({});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.source).toBe('demo');
expect(result.incidents.length).toBeGreaterThan(0);
}
});
it('filters demo incidents by state', async () => {
const allDemo = getDemoIncidentSummaries();
const openCount = allDemo.filter((i) => i.currentState === 'open').length;
const result = await fetchIncidentList({ state: 'open' });
if (result.ok) {
expect(result.incidents.every((i) => i.currentState === 'open')).toBe(true);
expect(result.incidents.length).toBe(openCount);
}
});
it('filters demo incidents by severity', async () => {
const result = await fetchIncidentList({ severity: 'high' });
if (result.ok) {
expect(result.incidents.every((i) => i.severity === 'high')).toBe(true);
}
});
it('filters demo incidents by project slug', async () => {
const allDemo = getDemoIncidentSummaries();
const firstSlug = allDemo[0].projectSlug;
const result = await fetchIncidentList({ project: firstSlug });
if (result.ok) {
expect(result.incidents.every((i) => i.projectSlug === firstSlug)).toBe(true);
}
});
it('filters demo incidents by query string', async () => {
const allDemo = getDemoIncidentSummaries();
const word = allDemo[0].title.split(' ')[0].toLowerCase();
const result = await fetchIncidentList({ q: word });
if (result.ok) {
expect(result.incidents.length).toBeGreaterThan(0);
}
});
it('returns empty list when no demo incidents match filter', async () => {
const result = await fetchIncidentList({ q: 'xyzzy_no_match_abc_999' });
if (result.ok) {
expect(result.incidents).toHaveLength(0);
}
});
});
describe('fetchIncidentDetail — demo mode', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
process.env.ERROR_REPORTING_UI_DEMO = '1';
});
afterEach(() => {
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns detail for a known demo incident', async () => {
const demos = getDemoIncidentSummaries();
const result = await fetchIncidentDetail(demos[0].id);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.incident.id).toBe(demos[0].id);
expect(result.source).toBe('demo');
}
});
it('returns not_found for an unknown demo id', async () => {
const result = await fetchIncidentDetail('no-such-incident-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_found');
}
});
});
describe('fetchIncidentDetail — not_configured', () => {
beforeEach(() => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
delete process.env.ERROR_REPORTING_UI_DEMO;
});
it('returns not_configured when API is not set and demo is off', async () => {
const result = await fetchIncidentDetail('some-id');
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBe('not_configured');
}
});
});
+146
View File
@@ -0,0 +1,146 @@
/**
* Tests for fetchOperationalStats covering the API-backed success and error paths.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchOperationalStats, type StatsSummaryPayload } from '@/lib/stats-data';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
const PREV_API_BASE = process.env.ERROR_REPORTING_ADMIN_API_BASE;
const mockSummary: StatsSummaryPayload = {
byProject: [
{ slug: 'wdmi', total: 5, open: 2, investigating: 1, resolved: 1, ignored: 1, critical: 0 },
],
bySeverity: { critical: 1, high: 2, medium: 1, low: 0, info: 0 },
resolvedLast24h: 3,
totalLast24h: 10,
};
const mockTrendDay = { granularity: 'day', dates: ['2026-01-01'], series: { high: [1] } };
const mockTrendHour = { granularity: 'hour', hours: ['2026-01-01 00:00:00'], series: { high: [1] } };
const mockRecurrence = { windowDays: 7, rangeStart: '2026-01-01', rangeEndExclusive: '2026-01-08', top: [] };
function makeFetchMock(responses: Map<string, unknown>) {
return vi.fn().mockImplementation((url: string) => {
for (const [key, value] of responses) {
if (url.includes(key)) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(value),
});
}
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
}
beforeEach(() => {
process.env.ERROR_REPORTING_ADMIN_API_BASE = 'http://test-api.local';
});
afterEach(() => {
if (PREV_API_BASE === undefined) {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
} else {
process.env.ERROR_REPORTING_ADMIN_API_BASE = PREV_API_BASE;
}
vi.restoreAllMocks();
});
describe('fetchOperationalStats — API mode', () => {
it('returns ok:true with all data when all fetches succeed', async () => {
global.fetch = makeFetchMock(
new Map([
['/v1/stats/summary', mockSummary],
['/v1/stats/trend?granularity=day', mockTrendDay],
['/v1/stats/trend?granularity=hour', mockTrendHour],
['/v1/stats/recurrence', mockRecurrence],
]),
);
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.summary.byProject).toHaveLength(1);
expect(result.trendDay.granularity).toBe('day');
expect(result.trendHour.granularity).toBe('hour');
expect(result.recurrence.windowDays).toBe(7);
}
});
it('returns error when summary fetch throws', async () => {
global.fetch = vi.fn().mockRejectedValue(new Error('network error'));
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.message).toContain('network error');
}
});
it('returns error when summary returns non-ok HTTP status', async () => {
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 503,
json: () => Promise.resolve({}),
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.message).toContain('503');
}
});
it('falls back to empty trendDay when trend day fetch fails', async () => {
let callCount = 0;
global.fetch = vi.fn().mockImplementation((url: string) => {
callCount++;
if (url.includes('/v1/stats/summary')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockSummary) });
}
if (url.includes('granularity=day')) {
return Promise.reject(new Error('day trend unavailable'));
}
if (url.includes('granularity=hour')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendHour) });
}
if (url.includes('recurrence')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockRecurrence) });
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.trendDay.dates).toHaveLength(0);
expect(result.trendHour.granularity).toBe('hour');
}
});
it('falls back to empty recurrence when recurrence fetch fails', async () => {
global.fetch = vi.fn().mockImplementation((url: string) => {
if (url.includes('/v1/stats/summary')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockSummary) });
}
if (url.includes('granularity=day')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendDay) });
}
if (url.includes('granularity=hour')) {
return Promise.resolve({ ok: true, json: () => Promise.resolve(mockTrendHour) });
}
if (url.includes('recurrence')) {
return Promise.reject(new Error('recurrence unavailable'));
}
return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({}) });
});
const result = await fetchOperationalStats();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.recurrence.top).toHaveLength(0);
}
});
});
+67
View File
@@ -0,0 +1,67 @@
import { describe, it, expect, vi } from 'vitest';
import { aggregateIncidentKpisFromSummary } from '@/lib/stats-data';
import type { StatsSummaryPayload } from '@/lib/stats-data';
import { fetchOperationalStats } from '@/lib/stats-data';
vi.mock('next/headers', () => ({
cookies: vi.fn().mockResolvedValue({ get: vi.fn().mockReturnValue(undefined) }),
}));
describe('fetchOperationalStats — not_configured', () => {
it('returns error when API is not configured', async () => {
delete process.env.ERROR_REPORTING_ADMIN_API_BASE;
const result = await fetchOperationalStats();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(typeof result.message).toBe('string');
}
});
});
describe('aggregateIncidentKpisFromSummary', () => {
it('returns zeros for empty byProject list', () => {
const summary: StatsSummaryPayload = { byProject: [] };
const result = aggregateIncidentKpisFromSummary(summary);
expect(result).toEqual({ total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 });
});
it('sums across a single project', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'proj-a', total: 10, open: 3, investigating: 2, resolved: 4, ignored: 1 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(10);
expect(result.open).toBe(3);
expect(result.investigating).toBe(2);
expect(result.resolved).toBe(4);
expect(result.ignored).toBe(1);
});
it('sums across multiple projects', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'proj-a', total: 5, open: 2, investigating: 1, resolved: 1, ignored: 1 },
{ projectSlug: 'proj-b', total: 8, open: 4, investigating: 2, resolved: 2, ignored: 0 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(13);
expect(result.open).toBe(6);
expect(result.investigating).toBe(3);
expect(result.resolved).toBe(3);
expect(result.ignored).toBe(1);
});
it('handles projects with all zeros', () => {
const summary: StatsSummaryPayload = {
byProject: [
{ projectSlug: 'empty', total: 0, open: 0, investigating: 0, resolved: 0, ignored: 0 },
],
};
const result = aggregateIncidentKpisFromSummary(summary);
expect(result.total).toBe(0);
});
});
+1
View File
@@ -0,0 +1 @@
import '@testing-library/jest-dom';
+23
View File
@@ -0,0 +1,23 @@
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'node:path';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./test/setup.ts'],
globals: true,
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
include: ['components/**/*.{ts,tsx}', 'lib/**/*.{ts,tsx}'],
exclude: ['**/*.d.ts', 'test/**'],
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
},
},
});