无法使用打字稿根据剧作家中的元素可见性执行 try catch 块

问题描述 投票:0回答:1

我有一个自动化场景,其中如果我看到页面的标题是“示例标题”,那么我可以将测试标记为通过。 否则,如果不可能,我必须单击页面上可用的其他内容,然后验证标题是否为“示例标题”。

我的代码: 我尝试使用 try catch 块,但不知怎的总是出现超时错误。以下是代码片段

try {
    await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 })
  }
  catch (error){
    await page.getByRole('link', { name: 'here' }).click();
    await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 })
  }

我期望的是脚本会先执行try块,当发生超时错误时它会被捕获,然后执行catch块。 但代码永远不会到达 catch 块。相反,我收到以下错误:

错误:

测试超时超过 30000ms。

Error: expect(locator).toHaveTitle(expected)

Locator: locator(':root')
Expected string: "Example title"
Received string: "Some Count Exceeded"
Call log:
  - expect.soft.toHaveTitle with timeout 30000ms
  - waiting for locator(':root')
  -   locator resolved to <html>…</html>
  -   unexpected value "dfretgrt"
  ...



>  19 |
      20 |   try {
    > 21 |     await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 })
         |                             ^
      22 |
      23 |   }
      24 |   catch (error){
typescript playwright
1个回答
0
投票

使用“OR”定位器。

创建一个与两个定位器中的任何一个相匹配的定位器。这可以在包括您在内的各种条件下使用。

使用示例

考虑这样一个场景:您想要单击“新电子邮件”按钮,但有时会显示安全设置对话框。在这种情况下,您可以等待“新电子邮件”按钮或对话框并采取相应行动。

const newEmail = page.getByRole('button', { name: 'New' });
const dialog = page.getByText('Confirm security settings');
await expect(newEmail.or(dialog)).toBeVisible();
if (await dialog.isVisible())
  await page.getByRole('button', { name: 'Dismiss' }).click();
await newEmail.click();

参考:https://playwright.dev/docs/api/class-locator#locator-or

© www.soinside.com 2019 - 2024. All rights reserved.