赛普拉斯获得href属性

Max*_*Max 27 javascript cypress

我有一个测试用例,其中我有一个链接在新选项卡中打开,并且由于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');
});
Run Code Online (Sandbox Code Playgroud)

Jen*_*ane 37

下面的代码应该做你想要实现的.还有一个完整的配方,提供有关如何测试在新选项卡中打开的链接的建议.

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)
     })
})
Run Code Online (Sandbox Code Playgroud)

我还建议阅读赛普拉斯文件,了解分配和使用变量的最佳方法:https://on.cypress.io/variables-and-aliases


Mob*_*ent 11

解决方案1: invoke("attr", "href")

导航到元素的href属性中指定的URL:

cy.get(selector)
      .invoke('attr', 'href')
      .then(href => {
        cy.visit(href);
      });
Run Code Online (Sandbox Code Playgroud)

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


解决方案2:禁止在新标签页中打开内容。

从锚元素中删除目标属性,然后单击该属性以导航到同一选项卡中的URL:

cy.get(selector).invoke('removeAttr', 'target').click()
Run Code Online (Sandbox Code Playgroud)

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