Mr.Prasad J
Mr.Prasad J

Reputation: 105

Cypress e2e testing: How to access new tab by clicking on "href". I don't have target attribute to remove and test on new opened tab?

This attached image is my HTML code for href which will open a new tab

The DOM has iframe so I wrote below code accessed the href and it will open in new tab. I am unable to access the newly opened tab, though I know the method that would have target attribute so we remove that and open in same tab but here I don't have any target attributes.

Please check this and help to access my new tab.

cy.visit('https://yopmail.com/en/')
cy.get('.ycptinput').type('some_name {enter}')
cy.wait(2000)
cy.get('#ifmail').its('0.contentDocument.body').then(cy.wrap).find('a').click()

Upvotes: 2

Views: 1189

Answers (1)

Fody
Fody

Reputation: 31904

The cy.origin() command is meant to solve the "new tab" problem.

It's a bit new, so expect some teething problems. Basically, it sets up a sand-boxed domain that can use Cypress commands.

Anything from outside cy.origin() that you want to use inside (for example, the link you found) needs special handling to pass in.

It gets passed in on a special args option, and is received in the same pattern.

let link;

cy.visit('https://yopmail.com/en/')
cy.get('.ycptinput').type('some_name {enter}')
cy.wait(2000)
cy.get('#ifmail').its('0.contentDocument.body')
  .then($body => {
    link = $body.find('a')[0].href
  })

cy.then(() => {          // this just waits for above block to complete

  const newOrigin = link.split('?')[0]  // remove query params 
      .replace('http://', 'https://')   // correct for secure protocol

  cy.origin(newOrigin, { args: { link } }, ({ link }) => {

    cy.visit(link)       // same as ".find('a').click()" but works cross-domain
  })
})
    

Upvotes: 3

Related Questions