【问题标题】:How to assert that a link is a link in Playwright如何断言链接是 Playwright 中的链接
【发布时间】:2022-06-22 01:25:24
【问题描述】:

我在这里尝试在 Playwright 中做一些断言,现在我需要断言在链接列表中所有链接都具有属性 href,但我不知道如何使用 Playwright 函数实现这一点。

我的代码在这里:

test.only('then a list of 44 links is displayed', async({ page }) => {
         const linkList = await page.locator('div#content > ul > li > a');
         for(let i = 0; i < await linkList.count(); i++) {
             expect(await linkList.nth(i)).toHaveAttribute('href', '');             }
         await expect(linkList).toHaveCount(44);
    })

toHaveAttribute() 函数需要 2 到 3 个参数,因为它获取 key 属性和属性值,但我只需要检查它是否具有 href 属性。

我怎样才能做到这一点?

这是正在测试的网站: https://the-internet.herokuapp.com/

【问题讨论】:

    标签: javascript html automated-tests playwright


    【解决方案1】:

    在尝试了一些选项之后,我意识到我可以断言使用 Locator.getAttribute('href') 时是否不返回 null,所以这是一个链接。 所以我实现了:

          const linkList = await page.locator('div#content > ul > li > a');
          for(let i = 0; i < await linkList.count(); i++) {
            expect(await linkList.nth(i).getAttribute('href')).not.toBeNull();
          }

    【讨论】:

      【解决方案2】:

      您可以使用Playwright's toHaveAttribute() method 来检查HTML 元素是否具有href 属性,如下所示:

      <a id="about-us" href="about-us.html" target="_blank">About Us</a>
      
      const aboutLink = page.locator("#about-us");
      await expect(homeLink).toHaveAttribute("href", "about-us.html");
      

      【讨论】:

        猜你喜欢
        • 2022-11-09
        • 1970-01-01
        • 2016-07-20
        • 1970-01-01
        • 1970-01-01
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多