能否在Playwright的JSON测试报告中添加自定义字段(如页面URL)
可以给Playwright JSON测试报告添加自定义字段(含页面URL)
完全可以实现,核心思路是先在测试流程中存储自定义数据(比如页面URL),再通过自定义报告器将数据写入最终的JSON报告,下面是具体实现步骤:
方法一:通过test.info()存储+自定义JSON报告器输出
1. 在测试用例中存储页面URL
在访问页面后,把当前页面的URL存入测试的信息对象中,两种方式任选:
test('示例页面测试', async ({ page }) => { await page.goto('https://example.com'); // 方式1:用annotations存储 test.info().annotations.push({ type: 'pageUrl', description: page.url() }); // 方式2:直接给test.info()添加自定义属性 test.info().pageUrl = page.url(); });
2. 编写自定义JSON报告器
创建一个自定义报告器文件(比如custom-json-reporter.js),继承Playwright默认的JSON报告器,在测试结束时把自定义数据加入报告:
const { JsonReporter } = require('@playwright/test/reporter'); class CustomJsonReporter extends JsonReporter { onTestEnd(test, result) { // 先调用父类方法生成基础报告内容 super.onTestEnd(test, result); // 方式1:从annotations中提取页面URL const pageUrlAnnotation = test.info().annotations.find(item => item.type === 'pageUrl'); if (pageUrlAnnotation) { result.pageUrl = pageUrlAnnotation.description; } // 方式2:直接读取自定义属性(如果用方式2存储的话) if (test.info().pageUrl) { result.pageUrl = test.info().pageUrl; } } } module.exports = CustomJsonReporter;
3. 配置使用自定义报告器
在playwright.config.js里指定使用这个自定义报告器,并设置输出文件:
module.exports = { reporter: [['./custom-json-reporter.js', { outputFile: 'test-results.json' }]] };
方法二:用附件形式存储(适合简单场景)
如果只是临时需求,也可以把页面URL作为文本附件加入测试信息,最终会出现在JSON报告的attachments数组里:
test('示例测试', async ({ page }) => { await page.goto('https://example.com'); await test.info().attach('pageUrl', { content: page.url(), contentType: 'text/plain' }); });
这种方式不需要自定义报告器,但URL会放在attachments里,不如方法一的独立字段直观。
注意:不同版本的Playwright API可能略有差异,建议结合对应版本的官方文档调整代码。
内容的提问来源于stack exchange,提问作者asdfasdfasdfasdf
相关产品推荐
相关产品推荐

