Last active
July 5, 2018 05:54
-
-
Save tk-o/a26877105e64e2b1dadbc94f7e4593c5 to your computer and use it in GitHub Desktop.
Testing external redirects in Cypress.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
it('should go to external page after clicking on CTA button', () => { // it's not click per se - we use element's href attribute | |
cy.get('a[href*="redirect"]') //finds all redirect links | |
.each(($linkElement) => { | |
const internalUrl = $linkElement.attr('href'); | |
cy.log(`Checking redirect for ${internalUrl}`); | |
cy.getExternalRedirect(internalUrl) // gets 302 redirect | |
.as('externalRedirect'); // saves the request as alias for the assertions | |
cy.get('@externalRedirect') | |
.its('status') // extract status property from request | |
.should('be.equal', 302); // check if status set to 302 | |
cy.get('@externalRedirect') | |
.its('redirectedToUrl') // extract redirect url property from request | |
.should('not.be.empty'); // check if not empty | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Cypress.Commands.add('getExternalRedirect', (internalRedirectUrl) => { | |
cy.request(internalRedirectUrl).then((response) => { | |
const { body } = response; | |
const externalRedirectUrlParts = body.match(/\d+;URL=(.*)"/); // extract redirect url from meta[http-equiv="refresh"] | |
expect(externalRedirectUrlParts).not.to.be.null; | |
const externalRedirectUrl = externalRedirectUrlParts[1]; | |
expect(externalRedirectUrl).to.be.defined; | |
cy.request({ | |
url: externalRedirectUrl, | |
followRedirect: false // don't go to external page | |
}).then((redirectResponse) => { | |
const { status, headers } = redirectResponse; | |
const isInternalRedirect = status !== 302 && headers.location.includes(window.location.host); | |
if (isInternalRedirect) { // we're still on our page, dig deeper | |
cy.request({ | |
url: headers.location, | |
followRedirect: false // don't go to external page | |
}) | |
} else { | |
cy.wrap(redirectResponse); | |
} | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment