[英]Cypress get href attribute
我有一个测试用例,其中有一个在新选项卡中打开的链接。 由于赛普拉斯不支持多个选项卡,我想获取该链接的href
属性,然后在同一个选项卡中打开它。 我正在尝试这样做,但由于某种原因它不起作用。
it('Advertise link should refer to Contact page', () => {
var link = document.querySelector("div.footer-nav > ul > li:nth-child(2) > a").href;
cy.visit(link);
cy.title().should('include', 'Text');
});
下面的代码应该可以实现您想要实现的目标。 还有一个完整的配方,其中包含有关如何测试在新选项卡中打开的链接的建议。
it('Advertise link should refer to Contact page', () => {
cy.get('div.footer-nav > ul > li:nth-child(2) > a')
.should('have.attr', 'href').and('include', 'contact')
.then((href) => {
cy.visit(href)
})
})
我还建议阅读赛普拉斯文档,了解分配和使用变量的最佳方法: https ://on.cypress.io/variables-and-aliases
invoke("attr", "href")
导航到元素的 href 属性中指定的 URL:
cy.get(selector)
.invoke('attr', 'href')
.then(href => {
cy.visit(href);
});
参考: https ://docs.cypress.io/api/commands/invoke.html#Function-with-Arguments
从锚元素中删除目标属性,然后单击它以在同一选项卡中导航到其 URL:
cy.get(selector).invoke('removeAttr', 'target').click()
参考: https ://docs.cypress.io/examples/examples/recipes.html#Tab-Handling-and-Links
我解决了这个问题:
首先 - 检查 href 是否具有正确的值
第二 - 创建另一个访问该 href 的测试
在我的情况下,href 的值是硬编码的。
我在测试中使用了类似的东西:
cy.get('a').each(($el) => {
const herf = $el.attr('href');
cy.log(herf);
// then I will do your test:
cy.visit(link);
cy.title().should('include', 'Text');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.