0
0
Cypresstesting~5 mins

cy.url() assertions in Cypress

Choose your learning style9 modes available
Introduction

We use cy.url() assertions to check if the web page's address is correct during tests. This helps us make sure the user is on the right page.

After clicking a link, to confirm the browser navigated to the expected page.
When testing redirects to verify the URL changed as intended.
To check if query parameters are present in the URL after a search.
When verifying that login redirects to the dashboard URL.
To ensure the URL contains specific parts after an action, like a product ID.
Syntax
Cypress
cy.url().should('include', 'expected-part')
cy.url().should('eq', 'https://example.com/page')
cy.url().should('match', /regex/)

cy.url() gets the current page URL as a string.

Use .should() with assertions like include, eq, or match to check the URL.

Examples
Checks if the URL contains '/dashboard' anywhere.
Cypress
cy.url().should('include', '/dashboard')
Checks if the URL exactly matches the full string.
Cypress
cy.url().should('eq', 'https://example.com/login')
Checks if the URL matches the regular expression pattern for a product page with an ID number.
Cypress
cy.url().should('match', /\/products\/\d+/)
Sample Program

This test visits the homepage, clicks the login link, and asserts the URL includes '/login'.

Cypress
describe('URL assertion test', () => {
  it('checks URL after clicking login', () => {
    cy.visit('https://example.com')
    cy.get('a.login-link').click()
    cy.url().should('include', '/login')
  })
})
OutputSuccess
Important Notes

Always use clear and specific URL parts to avoid false positives.

Use cy.url() assertions to catch navigation errors early.

Combine with other assertions like checking page content for stronger tests.

Summary

cy.url() assertions help confirm the browser is on the right page by checking the URL.

Use .should() with include, eq, or match for flexible checks.

They are simple but powerful for testing navigation and redirects.