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

如何仅在所有测试用例通过时执行Playwright JS的teardown?

解决Playwright JS仅在全量测试通过后执行Teardown的方案

核心思路

Playwright默认的项目级teardown会无条件执行,要实现"仅全量测试通过才执行销毁",最简单可靠的方式是通过CLI命令的执行顺序+退出码判断来控制teardown的触发,而非依赖配置文件中的teardown字段绑定。

具体实现步骤

1. 修改Playwright配置文件

移除setup项目中的teardown绑定,避免无条件触发销毁脚本:

projects: [
  {
    name: 'setup',
    testMatch: 'test.list.js'
    // 删掉原来的teardown: 'myTeardown'配置
  },
  {
    name: 'myTeardown',
    testMatch: /destroy\.all\.js/,
    use: {
      ...devices['Desktop Chrome'],
      headless: false
    },
  },
  {
    name: 'chromium',
    use: {
       ...devices['Desktop Chrome'],
       headless: false,
       dependencies: ['setup']
    },
  },
]

2. 通过npm脚本控制执行逻辑

在项目的package.json中添加组合脚本,利用shell的&&逻辑(前序命令成功才执行后续命令)来控制teardown的执行:

{
  "scripts": {
    "test": "playwright test && playwright test --project=myTeardown",
    "test-only": "playwright test",
    "teardown-manual": "playwright test --project=myTeardown"
  }
}

逻辑说明

  • 运行npm run test时,会先执行所有测试用例:
    • 如果所有测试通过,playwright test的退出码为0,会自动执行后续的myTeardown项目销毁脚本;
    • 如果有任意测试失败,playwright test的退出码非0,后续的销毁脚本会直接跳过。
  • 保留test-only和teardown-manual脚本,方便单独执行测试或手动触发销毁。

内容的提问来源于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.27 07:50:16