Another post from the series “Pinches of Cypress”
Continuing the series, learn how to verify that the user is redirected to the correct URL after a certain action.
Imagine a logout test scenario.
Let's say that after logging out of the application, the user is redirected to the login page. How to test that?
The answer is simple.
cy.url()
Let's look at an example.
describe('Logout', () => {
beforeEach(() => {
cy.login() // I'll talk about custom commands in another post. Stay tuned!
})
it('is redirected to the login page on log out', () => {
cy.contains('Logout')
.should('be.visible')
.click()
cy.url()
.should('be.equal', 'https://example.com/login')
})
})
With the return of the .url()
function call, we can verify that it is the same as an expected URL.
Let's look at another option, in case the baseUrl
property is defined in the cypress.config.js
file.
describe('Logout', () => {
beforeEach(() => {
cy.login()
})
it('is redirected to the login page on log out', () => {
cy.contains('Logout')
.should('be.visible')
.click()
cy.url().should(
'be.equal',
`${Cypress.config("baseUrl")}/login`
)
})
})
Tada! 🎉
With the JavaScript template strings functionality, we can obtain the baseUrl
configuration value (through Cypress.config (“baseUrl”)
) and interpolate it with the /login
value.
That way, we can run the same test in different environments (with different baseUrl
s), and everything will continue to work!
What do you think about the series?
I'm looking forward to hearing your feedback.
This post was originally published in Portuguese on the Talking About Testing blog.
Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.
Top comments (4)
On trying this, for some reason Cypress wasn't picking up the baseUrl from my config.
The workaround was to set it as an environment variable as per this doc
Thanks for sharing, Riley!
Nice one! Have you come across a situation where you need to assert on a redirection which goes out of your domain? In my case, I need to assert on a redirection which takes you to your auth provider. Is this even possible?
I've never had to do it. but I recommend reading the following issue on Cypress' GitHub github.com/cypress-io/cypress/issu...