import { Page } from '@playwright/test' import path from 'path' import fs from 'fs' export class ScreenshotHelper { private page: Page private screenshotDir: string constructor(page: Page, screenshotDir: string = './test-results/screenshots') { this.page = page this.screenshotDir = screenshotDir this.ensureDirectoryExists(screenshotDir) } private ensureDirectoryExists(dir: string) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }) } } async takeScreenshot(name: string): Promise { const timestamp = new Date().toISOString().replace(/[:.]/g, '-') const filename = `${timestamp}-${name}.png` const filepath = path.join(this.screenshotDir, filename) await this.page.screenshot({ path: filepath, fullPage: true }) return filepath } async takeElementScreenshot(selector: string, name: string): Promise { const timestamp = new Date().toISOString().replace(/[:.]/g, '-') const filename = `${timestamp}-${name}.png` const filepath = path.join(this.screenshotDir, filename) const element = await this.page.locator(selector) await element.screenshot({ path: filepath }) return filepath } async compareScreenshots(name: string, baselineDir: string = './test-results/baseline'): Promise { const baselinePath = path.join(baselineDir, `${name}.png`) const currentPath = await this.takeScreenshot(`${name}-current`) if (!fs.existsSync(baselinePath)) { console.warn(`Baseline screenshot not found: ${baselinePath}`) return false } // 这里可以添加图片比较逻辑 // 例如使用 pixelmatch 或其他图片比较库 return true } } export default ScreenshotHelper