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:
1 parent
989a92ba07
commit
3d4444eb21
33 files changed
+6374
-24
No files matched your search
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user