【问题标题】:How to use playwright expect to do an exact match of one of two possible values?如何使用剧作家期望对两个可能值之一进行精确匹配?
【发布时间】:2023-02-26 16:11:51
【问题描述】:

我如何使用 playwright expect 来检查两个完全匹配项之一?

这是我的功能。

export const assertThirdPartyInternetPath = async (
  page: Page,
  path: string,
) => {
  expect(page.url()).toBe(path);
};

我用它来测试维基百科页面的链接。

await this.assertThirdPartyInternetPath('https://en.wikipedia.org/wiki/Larry_Sanger'

但是,某些网站(如维基百科)会将移动设备(包括剧作家设备)重定向到 m 子域。

所以我想断言用户位于https://en.wikipedia.org/wiki/Larry_Sangerhttps://en.m.wikipedia.org/wiki/Larry_Sanger。我怎样才能做到这一点?

请注意,我要进行精确匹配;我知道我可以使用expect(string.toContain(myPattern),但我有很多东西要匹配,我想做精确匹配。

【问题讨论】:

    标签: playwright


    【解决方案1】:

    按照Jest matcher to match any one of three values 中的建议反转比较是可能的,但会使断言消息和整体流程有点尴尬。

    expect([
      "https://en.wikipedia.org/wiki/Larry_Sanger",
      "https://en.m.wikipedia.org/wiki/Larry_Sanger",
    ]).toContain(page.url());
    

    我更喜欢使用正则表达式,因为它使断言保持在正常方向:

    expect(page.url())
      .toMatch(/^https://en.(?:m.)?wikipedia.org/wiki/Larry_Sanger$/);
    

    问题是可读性和记住转义正则表达式字符并添加锚点。您可以使用普通字符串和带有一些额外实用程序代码的 escape it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2015-02-18
      • 2021-10-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多