import { TestInfo } from '@playwright/test'; import * as fs from 'fs'; import * as path from 'path'; const RESULTS_DIR = path.join(process.cwd(), 'test-results', 'write-outputs'); /** * Attaches captured data to the test report and writes it to disk. * Used by all "write" type tests to persist their recorded output. */ export async function attachWriteResult( testInfo: TestInfo, data: Record, label = 'recorded-output', ): Promise { if (!fs.existsSync(RESULTS_DIR)) { fs.mkdirSync(RESULTS_DIR, { recursive: true }); } const sanitizedTitle = testInfo.title.replace(/[^a-z0-9-_]/gi, '_').slice(0, 100); const filePath = path.join(RESULTS_DIR, `${sanitizedTitle}.json`); const output = { testId: testInfo.title, capturedAt: new Date().toISOString(), status: 'recorded', data, }; fs.writeFileSync(filePath, JSON.stringify(output, null, 2), 'utf-8'); await testInfo.attach(label, { body: JSON.stringify(output, null, 2), contentType: 'application/json', }); }