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

如何在Playwright TypeScript中获取当前测试名称?(附NUnit实现示例)

获取Playwright TypeScript中当前测试的名称

在Playwright的TypeScript测试框架里,你可以通过test.info()对象获取当前测试的相关元信息,这和你在NUnit中依赖TestContext的思路完全对应。下面是具体的实现方案:

基础用法:在测试用例内直接获取

直接在测试函数内部调用test.info(),就能拿到测试名称、所属套件等信息。对应你NUnit里ClassName.MethodName的格式,我们可以这样组合:

import { test } from '@playwright/test';

// 单独测试用例
test('单个测试示例', async ({ page }) => {
  const testInfo = test.info();
  // 若没有套件,直接返回测试名称;有套件则组合成「套件.测试名」格式
  const testClassMethod = testInfo.parent?.title 
    ? `${testInfo.parent.title}.${testInfo.title}` 
    : testInfo.title;
  
  console.log(testClassMethod); // 输出:单个测试示例
});

// 带测试套件的场景
test.describe('用户管理测试套件', () => {
  test('创建用户用例', async ({ page }) => {
    const testInfo = test.info();
    const testClassMethod = `${testInfo.parent!.title}.${testInfo.title}`;
    
    console.log(testClassMethod); // 输出:用户管理测试套件.创建用户用例
    // 你的测试逻辑...
  });
});

封装成可复用工具函数

如果你想像NUnit那样封装成通用方法,可以写一个工具函数,注意要在测试上下文范围内调用:

import { test } from '@playwright/test';

export function getTestClassMethod(): string {
  const testInfo = test.info();
  const suiteName = testInfo.parent?.title;
  return suiteName ? `${suiteName}.${testInfo.title}` : testInfo.title;
}

// 使用示例
test.describe('订单流程测试', () => {
  test('提交订单用例', async ({ page }) => {
    console.log(getTestClassMethod()); // 输出:订单流程测试.提交订单用例
    // 测试逻辑代码...
  });
});

额外说明

  • test.info()返回的TestInfo对象还包含很多实用信息:比如测试状态、参数化测试的参数值、测试文件路径等,你可以根据需求扩展使用。
  • 如果是参数化测试,testInfo.title会自动带上参数标识,比如"参数化测试 (user1)"这类格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:03:11