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

如何用Playwright JS实现A1文件夹测试通过后再执行B1文件夹测试?

实现Playwright JS按条件顺序执行测试文件夹

要实现仅当A1文件夹测试全部通过才执行B1的需求,最直接的方式是通过自定义Node.js脚本控制测试执行流程,利用Playwright CLI的退出码判断测试结果:

方法1:自定义执行脚本

  1. 在项目根目录创建一个名为run-tests.js的脚本文件,内容如下:
const { execSync } = require('child_process');

try {
  // 执行A1文件夹下的所有测试
  console.log('=== 开始执行A1文件夹测试 ===');
  execSync('npx playwright test A1/', { stdio: 'inherit' });

  // A1测试全部通过时,继续执行B1的测试
  console.log('\n=== A1测试全部通过,开始执行B1文件夹测试 ===');
  execSync('npx playwright test B1/', { stdio: 'inherit' });
} catch (err) {
  // A1测试失败时,终止后续流程并提示
  console.error('\n=== A1测试存在失败,终止执行后续测试 ===');
  process.exit(1);
}
  1. 在package.json中添加执行脚本:
"scripts": {
  "test:sequential": "node run-tests.js"
}
  1. 运行测试:
npm run test:sequential

原理说明

  • execSync会同步执行Playwright CLI命令,stdio: 'inherit'会把测试的输出直接打印到控制台,方便查看执行过程。
  • Playwright CLI在测试全部通过时会返回退出码0,若存在失败则返回非0值,此时execSync会抛出错误,触发catch块终止流程,不再执行B1的测试。

方法2:利用Playwright串行测试配置(可选)

如果希望在Playwright测试文件中直接控制流程,可以将A1和B1的测试逻辑整合到一个测试套件中,使用串行执行模式并判断前序测试结果:

const { test, expect } = require('@playwright/test');

let a1TestsPassed = true;

test.describe.configure({ mode: 'serial' });

test.describe('A1文件夹测试', () => {
  // 引入A1文件夹的测试用例(需确保测试文件可被导入)
  // 示例:require('./A1/example.test.js');
  
  test.afterAll(() => {
    // 检查A1测试是否全部通过
    a1TestsPassed = test.info().status === 'passed';
  });
});

test.describe('B1文件夹测试', () => {
  test.beforeAll(() => {
    // 若A1测试失败,跳过所有B1测试
    test.skip(!a1TestsPassed, 'A1测试失败,跳过B1测试');
  });

  // 引入B1文件夹的测试用例
  // 示例:require('./B1/example.test.js');
});

注意事项

  • 这种方式需要确保测试用例可以被模块化导入,相对脚本方式灵活性稍低,更适合小型测试集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:40:11