如何断言HTML元素在剧作家中是有效的链接?
我正在尝试在< a> 的列表中,所有这些都有属性 href
。但是,我不知道如何通过剧作家的功能实现这一目标。
我的代码在这里:
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个参数,因为它获取了密钥属性和属性的值,但是我只需要检查它是否具有HREF attr。
我该如何实现?
这是正在测试的网站: https://the-internet.herokuapp.com/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一些选项后,我意识到我可以断言是否使用locator.getAttribute('href')不会返回null,所以这是一个链接。
所以我实施了:
After trying some options, I realize that I can assert if when using Locator.getAttribute('href') does not return null, so that's a link.
So I implemented that:
感觉剧作家并不是最好的工具!如果链接在您的版本控件中,或者确保数据库查询只能以有效的HREF开始,则可以更好地完成索引。
比任何浏览器测试都要快得多,可以使事情保持动态,因此在添加或删除链接时,您不必修改测试。
但是,如果您想与剧作家一起做,而代码少于其他建议, and 以生成良好的习惯,以实现出色的可访问性测试,则可以使用
.getByrole < /代码>选择器。
带有HREF的锚元素具有“链接”角色,而没有它们是“通用”:
“ nofollow noreferrer”> https://www.w3.org/tr/html-aria/#docconformance
使用
byrole
定位器有助于确保您在语义上正确&amp;可访问元素:https://playwright.dev/dev/docs/docs/locators.locators.locators#locate-byby-rocati
在这种情况下,实际上具有HREF的锚标签!
因此,您可以做类似的事情:
您可能会链接另一个定位器,而不是查询整个页面,因此您只能在您感兴趣的部分中查询。
It feels like Playwright isn't the best tool for this! Feels like it'd be better done by linting if the links are in your version control, or ensuring your database query only fetches rows with a valid href to begin with.
Much faster to catch the problem than any browser test, and would keep things dynamic so you don't have to amend the test when you add or remove a link.
However, if you do want to do it with Playwright, with less code than the other suggestion, and to generate good habits for great tests for accessibility, you can do it with a
.getByRole
selector.Anchor elements with an href have the "link" role, without they are "generic":
https://www.w3.org/TR/html-aria/#docconformance
Using the
byRole
locators helps ensure you've got semantically correct & accessible elements:https://playwright.dev/docs/locators#locate-by-role
In this case, anchor tags that actually have hrefs!
So you could do something like:
Instead of querying the whole page, you'd probably chain another locator, so you only query within the section you're interested in.