Cypress:检查新打开的选项卡是否具有正确的 URL

Mar*_*cin 8 cypress

如果我的网站中有一个链接。例如。<a href="//google.com" target="_blank">go to Google</a>我想做一个测试:

  • 给定链接(html 标签a
  • 当点击链接时
  • 然后浏览器打开新选项卡,并且该选项卡的 URL 包含“google.com”

我知道这行不通

cy.get('a').click();
cy.url().should('include', 'google.com');
Run Code Online (Sandbox Code Playgroud)

jjh*_*ero 8

由于a有一个target属性,您可以执行此操作。

cy.get('a')
  .should('be.visible')
  .then(($a) => {
     expect($a).to.have.attr('target','_blank')
     // update attr to open in same tab
     $a.attr('target', '_self')
  })
  .click()
cy.url().should('include', 'google.com')
Run Code Online (Sandbox Code Playgroud)

根据您的应用程序和您想要测试的内容,使用cy.request()和检查 200 状态代码可能足以满足外部 URL 的要求。


Ala*_*Das 7

您可以使用removeAttr删除目标,然后单击链接并断言。就像是:

cy.get('a').invoke('removeAttr', 'target').click()
cy.url().should('include', 'google.com')
Run Code Online (Sandbox Code Playgroud)