乐闻世界logo
搜索文章和话题

Cypress 如何获取元素的 ` href `属性?

7 个月前提问
3 个月前修改
浏览次数90

3个答案

1
2
3

在Cypress中,要获取元素的href属性,你可以使用.invoke('attr', 'attributeName')方法,其中attributeName就是你想要获取的属性名,比如href。下面是一个简单的例子说明如何获取一个链接(anchor tag <a>)的href属性:

javascript
// 假设有一个链接<a id="my-link" href="/some-path">Click here</a> // 用Cypress选择这个元素然后获取href属性 cy.get('#my-link') // 选择元素 .invoke('attr', 'href') // 获取href属性 .then(href => { // 现在你可以使用href变量,它包含了链接的href属性值 console.log(href); // 输出: /some-path // 做其他的断言或操作 });

在这个例子中,.get('#my-link')命令先选中ID为my-link的元素,然后.invoke('attr', 'href')命令用于获取该元素的href属性值。最后,.then()用于得到这个属性值,并且可以在这个回调函数中对href进行进一步的操作或断言。

如果你需要断言这个href属性是否有特定的值,你可以直接用Cypress提供的.should()断言方法,例如:

javascript
// 断言元素的href属性是否等于某个特定值 cy.get('#my-link').should('have.attr', 'href', '/some-path');

在这个断言中,should('have.attr', 'href', '/some-path')会检查选中的元素是否有一个href属性,且该属性的值为/some-path。如果不匹配,测试会失败。

2024年6月29日 12:07 回复

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.

shell
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

2024年6月29日 12:07 回复

Solution 1: invoke("attr", "href")

Navigate to the URL specified in the element's href attribute:

shell
cy.get(selector) .invoke('attr', 'href') .then(href => { cy.visit(href); });

Reference: https://docs.cypress.io/api/commands/invoke.html#Function-with-Arguments


Solution 2: Prevent content from opening in a new tab.

Remove the target attribute from the anchor element, then click on it to navigate to its URL within the same tab:

shell
cy.get(selector).invoke('removeAttr', 'target').click()

Reference: https://docs.cypress.io/examples/examples/recipes.html#Tab-Handling-and-Links

2024年6月29日 12:07 回复

你的答案