Biopsy Alternator
Biopsy Alternator

Reputation: 1

How to handle multiple redirects to different origins in Cypress

I need to visit a URL that redirects twice to different origins. e.g:

domain-to-visit.com -> redirect1.com -> final-domain.com

This code below works for a single redirect:

cy.origin('redirect1.com') => {
  cy.visit('domain-to-visit.com');
}); 

But I need to support more than one redirect.

My reflex is to want to wrap the above code in another cy.origin but that is not supported yet.

How can I visit domain-to-visit.com and allow it to redirect to multiple origins in Cypress?

Upvotes: 0

Views: 2332

Answers (1)

Fody
Fody

Reputation: 31862

Just write an origin command for any redirect URL you are interested in testing something on.

If you have domain-to-visit.com -> redirect1.com -> final-domain.com and want to take action in final-domain.com, your code would be

cy.visit('domain-to-visit.com');

// you can ignore the intermediate domain "redirect1.com"

cy.origin('final-domain.com') => {
  cy.get(...).should(...)           // test this page
})

Testing the intermediate page

If you want to also test something on redirect1.com, just add another cy.origin(), not nested but sequentially.

This only makes sense if the web page needs an action to go to the final page, as far as I can see.

cy.visit('domain-to-visit.com');

cy.origin('redirect1.com') => {
  cy.get(...).should(...)           // test this page
  cy.get('a[href="..."]').click()   // redirect onwards
})

cy.origin('final-domain.com') => {
  cy.get(...).should(...)           // test this page
})

A reproducible example

base-page.html

Uses HTML redirect in <meta> tag

<html>
  <head>
    <meta http-equiv="refresh" content="0; URL='http://127.0.0.1:5500/html/redirect1.html'" />
  </head>
  <body>
    <h1>Base page</h1>
  </body>
</html>

Served on port 3000:

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'text/html' })
  fs.createReadStream('html/base-page.html').pipe(res)
})
server.listen(process.env.PORT || 3000)

redirect1.html

Uses javascript redirect on button click.

Served on port 5500:

<html>
  <body>
    <h1>Redirect 1</h1>
    <button onclick="redirect()">Redirect</button>
    <script>
      function redirect() {
        window.location = "https://example.com"
      }
    </script>
  </body>
</html>

Test

cy.visit('http://127.0.0.1:3000')
cy.get('h1').contains('Base page')                                // passes

cy.origin('http://127.0.0.1:5500/html/redirect1.html', () => {
  cy.get('h1').contains('Redirect 1')                             // passes
  cy.get('button').contains('Redirect').click()
})  

cy.origin('https://example.com', () => {
  cy.get('h1').contains('Example Domain')                         // passes
})

enter image description here

Upvotes: 6

Related Questions