【问题标题】:How can I assert that an element is NOT on the page in playwright?我如何断言某个元素不在剧作家的页面上?
【发布时间】:2022-08-03 06:25:57
【问题描述】:

我正在测试一个包含徽标的 PWA,并且我想确保徽标不会出现在某些页面上。

如何断言元素不存在?我检查了Playwright assertions documentation,但它只有检查确实存在的东西的例子。

由于剧作家要求我们await一切,我想到了做这样的事情:

async assertNoLog(): Promise<boolean> {
  await this.page.locator(\'div#page-id\');
  // Now check if logo is on page.
}

但是我不确定要写什么来实际搜索徽标。

    标签: playwright


    【解决方案1】:

    您可以使用您希望元素具有的条件。例如,在 Playwright 的主页上,您希望 .navbar__brand 类的元素可见,但您也希望 .notexists 类的元素不可见(在这种情况下,该元素将不存在)。然后你可以这样做:

    test('element does exist @pass', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      const locator = await page.locator('.navbar__brand').isVisible();
      expect(locator).toBeTruthy();
    });
    
    test('element does NOT exist @fail', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      const locator = await page.locator('.notexists').isVisible();
      expect(locator).toBeTruthy();
    });
    

    当然,这样做会返回相同的结果:

    test('element does exist @pass', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      expect(await page.locator('.navbar__brand').isVisible()).toBe(true);
    });
    
    test('element does NOT exist @fail', async ({ page }) => {
      await page.goto('https://playwright.dev/');
      expect(await page.locator('.notexists').isVisible()).toBe(true);
    });
    

    正如我所说,元素的条件取决于你。例如,如果你想断言一个具有可见性的元素:hidden 也不存在于 DOM 中,因为它根本不应该存在,你可以将可见性和 .isHidden() 条件包装在 if/else 等中。当然,您可以随意使用布尔值(toBe(true)/toBe(false)、toBeTruthy()/toBeFalsy())。

    这些不是最优雅的解决方案,但我希望它们能提供帮助。

    【讨论】:

      【解决方案2】:

      您可以使用 .count() 并断言它返回 0。

      await expect(await page.locator('.notexists').count()).toEqual(0);
      

      https://playwright.dev/docs/api/class-locator#locator-count

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-09
        • 1970-01-01
        • 2020-08-10
        • 2022-11-14
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多