【问题标题】:Cypress get href attribute赛普拉斯获取 href 属性
【发布时间】:2018-06-29 02:56:53
【问题描述】:

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

【问题讨论】:

  • “它不起作用”你能更清楚一点吗?你看到了什么具体的行为,你想看到什么?
  • 其他一些需要考虑的事情 - 1) var link 是否获得正确的路径 2) 你是否在浏览器中对其进行了测试 3) visit() 是否需要 cy.wait() 来解决页面?

标签: javascript cypress


【解决方案1】:

下面的代码应该可以实现您想要实现的目标。还有一个完整的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)
     })
})

我还建议通读 Cypress 文档,了解分配和使用变量的最佳方法:https://on.cypress.io/variables-and-aliases

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这是一种了不起的方法,可以在不进入新标签的情况下继续测试新标签中发生的事情,这在赛普拉斯中不受支持。非常感谢!
    【解决方案3】:

    我解决了这个问题:

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

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

    在我的例子中,href 的值是硬编码的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多