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

Walmyr - Feb 6 '21 - - Dev Community

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.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`
    )
  })
})
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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player