DEV Community

loading...
Cover image for How to check that I was redirected to the correct URL with Cypress

How to check that I was redirected to the correct URL with Cypress

Walmyr Filho
I'm a software engineer that loves testing. I'm also a clean coder, blogger, YouTuber, Cypress.io Ambassador, writer, online teacher, mentor, consultant, speaker, an active member of tech communities.
Updated on ・2 min read

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')
  })
})
Enter fullscreen mode Exit fullscreen mode

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.json 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`
    )
  })
})
Enter fullscreen mode Exit fullscreen mode

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 baseUrls), 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.

Discussion (2)

Collapse
elninoisback profile image
Ε Γ И І И О

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?

Collapse
walmyrlimaesilv profile image
Walmyr Filho Author

I've never had to do it. but I recommend reading the following issue on Cypress' GitHub github.com/cypress-io/cypress/issu...