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

Playwright Cucumber TypeScript软断言未按预期工作,失败后终止后续步骤

Playwright Cucumber TypeScript 软断言失效问题解决

在Playwright结合Cucumber和TypeScript的场景中,使用expect.soft()时会出现断言失败后直接终止场景、不执行后续步骤的问题,这不符合软断言“继续执行并收集所有失败”的预期。

问题原因

Cucumber默认会在捕获到未处理的异常时立即终止当前测试场景,而Playwright的expect.soft()虽然不会同步抛出错误,但如果不对其失败结果进行捕获,最终仍会触发Cucumber的终止逻辑。

解决方案:手动收集软断言错误并延迟抛出

通过在Cucumber的World对象中维护错误列表,捕获每个软断言的失败,最后在场景结束时统一抛出所有错误,实现软断言的预期效果。

1. 定义自定义World类

用于存储软断言的失败信息:

import { World, IWorldOptions } from '@cucumber/cucumber';

export class CustomWorld extends World {
  softAssertionErrors: Error[] = [];

  constructor(options: IWorldOptions) {
    super(options);
    this.softAssertionErrors = [];
  }
}

2. 修改步骤定义,捕获软断言失败

在步骤中用try/catch捕获软断言的错误,存入World的错误列表:

When('I should see that heading {string} is visible on Screen', async function (headingText) {
  try {
    await expect.soft(page.getByRole('heading', { name: headingText })).toBeVisible();
  } catch (error) {
    this.softAssertionErrors.push(error as Error);
  }
});

3. 添加After钩子,统一抛出错误

在每个场景结束后检查错误列表,存在失败则汇总抛出:

import { After } from '@cucumber/cucumber';

After(async function () {
  if (this.softAssertionErrors.length > 0) {
    const errorSummary = this.softAssertionErrors
      .map((err, index) => `${index + 1}. ${err.message}`)
      .join('\n');
    throw new Error(`软断言失败汇总:\n${errorSummary}`);
  }
});

这样设置后,即使某一步的软断言失败,后续步骤仍会继续执行,直到场景结束才会抛出所有软断言的失败信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:35:04