You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright配置文件中获取测试名称?

在Playwright配置文件中动态获取测试信息(如testInfo.title)的方案

核心问题

playwright.config.ts是测试启动前就加载完成的,而testInfo是测试用例执行时才创建的运行时上下文对象,所以直接在配置的静态字段里引用testInfo会报错。

可行解决方案

方案1:使用测试钩子动态修改输出路径

在测试文件或全局钩子文件中,通过testInfo动态设置当前测试的输出目录:

// 测试文件example.spec.ts
import { test } from '@playwright/test';

test.beforeEach(async ({}, testInfo) => {
  // 动态指定当前测试的输出文件夹
  testInfo.outputDir = `reportLocation/${testInfo.title}`;
});

test('示例测试用例', async ({ page }) => {
  await page.goto('https://example.com');
  // 测试逻辑...
});

方案2:使用自定义报告器统一处理

如果需要统一管理所有测试的输出路径,可以自定义报告器,在报告器逻辑中访问测试标题并处理存储路径:

// 自定义报告器文件custom-reporter.ts
import { Reporter, TestCase, TestResult } from '@playwright/test/reporter';

class CustomReporter implements Reporter {
  onTestEnd(test: TestCase, result: TestResult) {
    const targetPath = `reportLocation/${test.title}`;
    // 在这里执行报告生成、文件拷贝等逻辑
  }
}

export default CustomReporter;

然后在playwright.config.ts中配置该报告器:

// playwright.config.ts
import { defineConfig } from '@playwright/test';
import CustomReporter from './custom-reporter';

export default defineConfig({
  reporter: [['list'], [CustomReporter]],
});

注意事项

  • 禁止在playwright.config.ts的顶层配置字段(如outputFolder)中直接引用testInfo,此时测试上下文尚未初始化,会直接报错。
  • 全局生效的逻辑优先放在全局钩子或自定义报告器中,避免在每个测试文件重复编写代码。

内容的提问来源于stack exchange,提问作者XZORPHIT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:02:43