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

如何在Playwright中断言两种不同的预期文本内容?

在Playwright中断言文本为两个可能值之一的解决方案

你当前的代码问题在于:同一个元素的文本在同一测试场景下只会是其中一个值,两个toBe()断言顺序执行时,第一个通过后第二个必然失败——因为元素文本不可能同时等于两个不同的字符串。

以下是几种可行的解决方式:

方式一:使用toBeOneOf匹配器(推荐)

Playwright内置了toBeOneOf匹配器,可直接断言目标值属于指定的候选数组:

async verifyParticipantEligibility() {
  const statusText = await this.participantStatus.textContent();
  expect(statusText).toBeOneOf(['Screened - Ineligible', 'Can be re-screened']);
}

方式二:用数组包含判断

先获取文本内容,再断言该内容存在于预期值数组中:

async verifyParticipantEligibility() {
  const statusText = await this.participantStatus.textContent();
  expect(['Screened - Ineligible', 'Can be re-screened']).toContain(statusText);
}

方式三:根据测试分支拆分断言(适合不同操作对应不同结果的场景)

如果这两个文本对应不同的用户操作分支(比如选择选项A后显示文本1,选择选项B后显示文本2),建议将断言逻辑拆分到对应分支中,或给方法传入预期值:

// 封装通用断言方法
async verifyParticipantEligibility(expectedStatus: string) {
  expect(await this.participantStatus.textContent()).toBe(expectedStatus);
}

// 对应不同操作场景调用
// 选择特定选项A后验证
await this.verifyParticipantEligibility('Screened - Ineligible');
// 选择特定选项B后验证
await this.verifyParticipantEligibility('Can be re-screened');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:12:34