如何使用MS Playwright将自定义截图附加到Allure测试报告中
Playwright主动添加截图到Allure报告不显示的解决方法
问题修复步骤
- 补全allure实例导入
在测试文件顶部添加导入语句:
import { allure } from 'allure-playwright';
- 配置Playwright Allure上报器
修改playwright.config.ts或playwright.config.js配置文件,添加allure上报规则:
const { defineConfig } = require('@playwright/test'); module.exports = defineConfig({ // 其余全局配置省略 reporter: [ ['allure-playwright'] // 其余上报器可共存,比如['html'] ], });
- 修正Allure附件上传API
旧版allure.screenshot已废弃,统一使用allure.attachment上传图片类附件,若需要截图展示在指定测试步骤下,需嵌套到allure.step回调中:
import { test, expect } from '@playwright/test'; import { allure } from 'allure-playwright'; test('basic test', async ({ page }) => { await page.goto('https://playwright.dev/'); // 如需截图挂载在步骤内,用step包裹 await allure.step('截取首页全屏', async () => { const screen1 = await page.screenshot({ fullPage: true }); // 调用attachment方法上传截图 allure.attachment('screenShot', screen1, 'image/png'); }) const title = await page.locator('.navbar__inner .navbar__title'); await expect(title).toHaveText('Playwright'); await page.close(); });
- 执行正确的报告生成流程
测试执行完成后需先生成静态报告再打开:
- 运行测试:
npx playwright test - 确认项目根目录生成
allure-results文件夹,内部包含.png格式的附件文件 - 生成报告:
npx allure generate allure-results --clean - 预览报告:
npx allure open allure-report
如果提示allure命令不存在,先全局安装命令行工具:npm i -g allure-commandline
- 兼容版本升级
如果以上操作均完成仍无法显示,可升级依赖到最新兼容版本:npm i -D @playwright/test@latest allure-playwright@latest
内容的提问来源于stack exchange,提问作者user5199
相关产品推荐
相关产品推荐

