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

如何使用Playwright注解运行指定测试步骤?

在Playwright中基于标签控制测试步骤的执行

Playwright的test.step自带的tag属性仅用于标记,不会自动控制步骤是否执行,你可以通过以下两种方式实现需求:

方法一:在步骤内判断标签是否存在

通过读取测试上下文的注解,或者检查命令行参数,判断是否执行目标步骤,无需拆分测试:

test('Test for some feature 1', async ({page}) => {
   await test.step('Step 1', async() => {
     // 预览相关断言逻辑
    });
  
  await test.step('Step 2', async() => {
    // 预览相关断言逻辑
    });
 
  // 检查当前测试是否包含@featureX标签
  const hasFeatureXTag = test.info().annotations.some(
    anno => anno.type === 'tag' && anno.description.includes('@featureX')
  );

  // 或者直接检查命令行是否传入了--grep @featureX参数
  // const hasFeatureXTag = process.argv.some(arg => arg.includes('@featureX'));

  if (hasFeatureXTag) {
    await test.step('Step 3', async() => {
      // 消息发送相关断言逻辑,仅当标签存在时执行
    });
  }
});

方法二:拆分子测试并添加标签

把消息发送的逻辑拆成子测试,给子测试打上标签,通过--grep参数控制是否运行:

test('Test for some feature 1', async ({page}) => {
   await test.step('Step 1', async() => {
     // 预览相关断言逻辑
    });
  
  await test.step('Step 2', async() => {
    // 预览相关断言逻辑
    });
 
  // 子测试仅当--grep @featureX时运行
  test('Step 3 - 消息发送验证', {tag: ['@featureX']}, async () => {
    // 消息发送相关断言逻辑
  });
});

运行方式

需要执行消息发送步骤时,运行命令:
npx playwright test --grep "@featureX"

这样既不会重复Step1、Step2的操作,又能独立验证预览效果,同时按需触发消息发送的测试逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:42:35