Javascript Cypress 获取 href 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48348354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cypress get href attribute
提问by Max
I have a test case in which i have a link which opens in a new tab, and since cypress doesn't support multi tab, i wanna get href attribute of that link and then open it in the same tab, i`m trying to do it this way, but for some reason it doesn't work.
我有一个测试用例,其中我有一个在新选项卡中打开的链接,由于 cypress 不支持多选项卡,我想获取该链接的 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');
});
回答by Jennifer Shehane
The code below should do what you're trying to achieve. There is also an entire recipe with suggestions on how to test links that open in new tabs.
下面的代码应该可以完成您想要实现的目标。还有一个完整的秘诀,其中包含有关如何测试在新选项卡中打开的链接的建议。
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)
})
})
I would also suggest reading through the Cypress document on the best ways to assign and work with variables: https://on.cypress.io/variables-and-aliases
我还建议通读 Cypress 文档,了解分配和使用变量的最佳方法:https: //on.cypress.io/variables-and-aliases
回答by Mobiletainment
Solution 1: invoke("attr", "href")
解决方案1: invoke("attr", "href")
Navigate to the URL specified in the element's href attribute:
导航到元素的 href 属性中指定的 URL:
cy.get(selector)
.invoke('attr', 'href')
.then(href => {
cy.visit(href);
});
Reference: https://docs.cypress.io/api/commands/invoke.html#Function-with-Arguments
参考:https: //docs.cypress.io/api/commands/invoke.html#Function-with-Arguments
Solution 2: Prevent content from opening in a new tab.
解决方案 2:防止在新标签页中打开内容。
Remove the target attribute from the anchor element, then click on it to navigate to its URL within the same tab:
从锚元素中删除目标属性,然后单击它以导航到同一选项卡中的 URL:
cy.get(selector).invoke('removeAttr', 'target').click()
Reference: https://docs.cypress.io/examples/examples/recipes.html#Tab-Handling-and-Links
参考:https: //docs.cypress.io/examples/examples/recipes.html#Tab-Handling-and-Links
回答by srgj
I resolved this issue:
我解决了这个问题:
First - check if href have right value
首先 - 检查 href 是否具有正确的值
Second - create another test in which visit that href
第二 - 创建另一个测试,在其中访问该 href
Value for href was hard coded in my case.
在我的情况下,href 的值是硬编码的。

