jquery - 无法使用 Cypress 在同一选项卡中打开链接

标签 jquery tabs cypress href

在我们的网页中,我们有各种在新选项卡中打开的链接,但显然我们在使用 Cypress 时需要在同一选项卡中打开它们。

我已经尝试过

cy.get('tr td:nth-child(9)').eq(index).invoke('removeAttr', 'target').click()

但这仍然会在新选项卡中打开 URL。

我还尝试添加 find('a') :

cy.get('tr td:nth-child(9)').eq(index).find('a').invoke('removeAttr', 'target').click()

但页面从未加载(我也尝试过增加超时时间,但仍然失败)。

我想让上面的代码工作,但我也发现了这个可行的替代方案,所以我想我对下面的代码感到困惑,但我无法让调用工作。

cy.get('tr td:nth-child(9)').eq(index).find('a').then(link => {
                   cy.request(link.prop('href')).its('status').should('eq', 200)

如有任何反馈,我们将不胜感激!谢谢

最佳答案

一般的做法是

cy.get('tr td:nth-child(9)').eq(index).find('a')
  .then($el => {
     expect($el).to.have.attr('target','_blank')
     // update attr to open in same tab
     $el.attr('target', '_self')
  })
  .click()

_self 值可能并不总是必需的,但另一个方面是更新 DOM 时的时间。

你也可以试试这个

cy.get('tr td:nth-child(9)').eq(index).find('a')
  .invoke('attr', 'href').then(myLink => {
    cy.visit(myLink);
  })

跨源

查看此博客 Stub window.open ,展示了一种将窗口 stub 打开的方法。

let stub    // variable that will hold cy.stub created in the test

Cypress.on('window:before:load', (win) => {
  if (stub) {
    Object.defineProperty(win, 'open', {
      get() {
        return stub
      }
    })
  }
})

beforeEach(() => {
  stub = null
})

const href = 'url/that/link/takes/you to'

it('check that window open was called', () => {

  cy.visit('/')  // not stubbing this

  stub = cy.stub().as('open')
  
  cy.get('tr td:nth-child(9)').eq(index).find('a')
    .click()    // trigger window.open

  cy.get('@open')
    .should('have.been.calledWith', href)   // check href is called

})

it('tests the link page further', () => {
  cy.visit(href)
  // continue tests
})

如果您的 href 是可变的,您可以在 beforeEach 中获取它

beforeEach(() => cy.visit('/'))

beforeEach(() => {
  cy.get('tr td:nth-child(9)').eq(index)
    .find('a').invoke('attr', 'href').as('href')   // link value into an alias
})

it('check that window open was called', () => {

  cy.get('@href').then(href => {
 
    stub = cy.stub().as('open')
  
    cy.get('tr td:nth-child(9)').eq(index).find('a')
      .click()    // trigger window.open

    cy.get('@open')
      .should('have.been.calledWith', href)   // check href is called
  })
})

it('tests the link page further', () => {
  cy.get('@href').then(href => {
    cy.visit(href)
    // continue tests
  })
})

关于jquery - 无法使用 Cypress 在同一选项卡中打开链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71125004/

相关文章:

javascript - 如何检测 contenteditable div 内的 HTML 更改?

javascript - 更新页面的一部分而不重新加载整个页面

Android TabLayout ViewPager 没有在 backstack 上膨胀选项卡 fragment

javascript - window.open 在 Google Chrome 中打开标签页和窗口

if-statement - Cypress - 如果那么起作用

testing - CircleCI + Cypress 配置

javascript - 为 Cypress 创建静态内容选择器

javascript - 如何在textarea中插入文本并转换<br>中的p而不看到其中的html?

c++ - 如何正确地将输出组织成列?

javascript - IFrame 中不会发生事件冒泡