import type { Page } from '@playwright/test'; /** * Evidence capture for failure reports (spec §42). Attach to a page to collect * console errors and failed network requests; `summary()` returns them for the * failure report. */ export class PageEvidence { consoleErrors: string[] = []; failedRequests: string[] = []; constructor(private page: Page) { page.on('console', (msg) => { if (msg.type() === 'error') this.consoleErrors.push(msg.text()); }); page.on('pageerror', (err) => this.consoleErrors.push(`pageerror: ${err.message}`)); page.on('requestfailed', (req) => { this.failedRequests.push(`${req.method()} ${req.url()} -> ${req.failure()?.errorText ?? 'failed'}`); }); page.on('response', (res) => { if (res.status() >= 400) this.failedRequests.push(`${res.request().method()} ${res.url()} -> ${res.status()}`); }); } /** A compact evidence block for the failure report. */ summary(): string { const parts: string[] = []; if (this.consoleErrors.length) parts.push(`Console errors:\n ${this.consoleErrors.join('\n ')}`); if (this.failedRequests.length) parts.push(`Failed requests:\n ${this.failedRequests.join('\n ')}`); return parts.length ? parts.join('\n\n') : '(no console errors or failed requests captured)'; } } /** * Build a spec §42 failure-report block. Call inside a test's catch or via a * custom expect message. */ export function failureReport(opts: { testId: string; testName: string; roles: string; preconditions: string; expected: string; actual: string; repro: string; evidence?: string; probableArea?: string; severity?: string; }): string { return [ `Test ID: ${opts.testId}`, `Test name: ${opts.testName}`, `Role(s): ${opts.roles}`, `Preconditions: ${opts.preconditions}`, `Expected: ${opts.expected}`, `Actual: ${opts.actual}`, `Reproduction: ${opts.repro}`, opts.evidence ? `Evidence:\n${opts.evidence}` : '', opts.probableArea ? `Probable implementation area: ${opts.probableArea}` : '', opts.severity ? `Severity: ${opts.severity}` : '', ] .filter(Boolean) .join('\n'); }