How to Assert URL in Cypress: Syntax and Examples
In Cypress, you can assert the current URL using
cy.url() combined with should() for assertions. For example, use cy.url().should('include', '/dashboard') to check if the URL contains '/dashboard'.Syntax
The basic syntax to assert the URL in Cypress uses cy.url() to get the current URL, followed by should() to make an assertion.
cy.url(): Fetches the current URL of the page.should('include', 'text'): Asserts that the URL contains the specified text.should('eq', 'full_url'): Asserts that the URL exactly matches the full URL string.should('match', /regex/): Asserts that the URL matches a regular expression.
javascript
cy.url().should('include', '/path') cy.url().should('eq', 'https://example.com/path') cy.url().should('match', /\/path\/?$/)
Example
This example demonstrates how to visit a page and assert that the URL contains a specific path segment.
javascript
describe('URL Assertion Test', () => { it('checks if URL includes /dashboard after login', () => { cy.visit('https://example.cypress.io') // Simulate login or navigation cy.get('a[href="/dashboard"]').click() // Assert URL contains '/dashboard' cy.url().should('include', '/dashboard') }) })
Output
Test passes if URL contains '/dashboard'; fails otherwise.
Common Pitfalls
Common mistakes when asserting URLs in Cypress include:
- Using
cy.location()incorrectly instead ofcy.url()for simple URL string assertions. - Asserting exact URL with
eqwithout considering trailing slashes or query parameters. - Not waiting for navigation to complete before asserting the URL.
Always ensure the page has fully loaded or navigation is complete before asserting the URL.
javascript
/* Wrong: Asserting exact URL without waiting or ignoring query params */ cy.url().should('eq', 'https://example.com/dashboard') /* Right: Use include to ignore query params or wait for navigation */ cy.url().should('include', '/dashboard')
Quick Reference
| Assertion Type | Usage | Description |
|---|---|---|
| Include | cy.url().should('include', '/path') | Checks if URL contains the given substring. |
| Equal | cy.url().should('eq', 'https://example.com/path') | Checks if URL exactly matches the string. |
| Match | cy.url().should('match', /regex/) | Checks if URL matches the regular expression. |
Key Takeaways
Use cy.url() with should() to assert the current page URL in Cypress.
Prefer 'include' assertion to avoid brittle tests due to query params or trailing slashes.
Wait for navigation or page load before asserting the URL to avoid flaky tests.
Use 'eq' for exact URL matches only when you control the full URL precisely.
Regular expressions with 'match' provide flexible URL pattern assertions.