65

我有一个测试用例,其中有一个在新选项卡中打开的链接。由于赛普拉斯不支持多个选项卡,我想获取该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');
});
4

4 回答 4

96

下面的代码应该可以实现您想要实现的目标。还有一个完整的配方,其中包含有关如何测试在新选项卡中打开的链接的建议

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

于 2018-01-25T20:13:18.923 回答
45

解决方案1: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


解决方案 2:阻止内容在新选项卡中打开。

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

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

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

于 2019-04-08T21:49:11.460 回答
0

我解决了这个问题:

首先 - 检查 href 是否具有正确的值

第二 - 创建另一个访问该 href 的测试

在我的情况下,href 的值是硬编码的。

于 2020-02-26T13:08:52.060 回答
0

我在测试中使用了类似的东西:

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');

});
于 2022-02-11T09:46:51.750 回答