Bird
Raised Fist0
Cypresstesting~15 mins

cy.url() assertions in Cypress - Deep Dive

Choose your learning style10 modes available
Overview - cy.url() assertions
What is it?
cy.url() assertions are commands in Cypress testing that check the current web page's URL during automated tests. They help verify that the browser is on the expected page by comparing the URL to a given value or pattern. This ensures the application navigates correctly and behaves as intended. Assertions are conditions that must be true for the test to pass.
Why it matters
Without checking the URL, tests might miss navigation errors or broken links, leading to bugs in live websites. cy.url() assertions catch these issues early by confirming the user is on the right page. This saves time and prevents users from facing confusing or wrong pages. It makes automated tests more reliable and trustworthy.
Where it fits
Before learning cy.url() assertions, you should understand basic Cypress commands and how to write simple tests. After mastering URL assertions, you can explore more complex navigation tests, chaining assertions, and testing dynamic URLs or query parameters.
Mental Model
Core Idea
cy.url() assertions check if the browser's current address matches what the test expects, confirming correct navigation.
Think of it like...
It's like checking the address on a letter before sending it to make sure it goes to the right house.
┌───────────────┐
│ Start Test    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Visit Page    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ cy.url()      │
│ gets current  │
│ URL           │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Assert URL    │
│ matches       │
│ expected      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Pass or Fail  │
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding cy.url() command
🤔
Concept: Learn what cy.url() does and how it retrieves the current page URL.
In Cypress, cy.url() is a command that gets the current URL of the browser. It returns a chainable object that you can use to make assertions. For example, cy.url().should('include', '/home') checks if the URL contains '/home'.
Result
You can access the current URL during a test and use it to verify navigation.
Knowing how to get the current URL is the first step to verifying if your app navigates correctly.
2
FoundationBasic URL assertion syntax
🤔
Concept: Learn how to write simple assertions on the URL using should() and expect().
You can write assertions like cy.url().should('eq', 'https://example.com/home') to check exact match, or cy.url().should('include', '/dashboard') to check if URL contains a part. You can also use expect syntax with cy.url().then(url => expect(url).to.contain('/profile')).
Result
Tests can confirm the URL matches expected values or patterns.
Understanding assertion syntax lets you check URLs precisely or loosely depending on test needs.
3
IntermediateUsing regex with cy.url() assertions
🤔Before reading on: do you think cy.url() can check URL patterns using regular expressions? Commit to yes or no.
Concept: Learn to use regular expressions to match complex URL patterns in assertions.
Cypress supports regex in assertions. For example, cy.url().should('match', /^https:\/\/example\.com\/user\/\d+$/) checks if the URL matches a pattern like 'https://example.com/user/123'. This is useful for dynamic URLs with IDs or tokens.
Result
You can verify URLs that change dynamically but follow a pattern.
Using regex in URL assertions allows flexible and powerful checks for real-world dynamic navigation.
4
IntermediateChaining multiple URL assertions
🤔Before reading on: can you chain multiple assertions on cy.url() in one statement? Commit to yes or no.
Concept: Learn to combine several checks on the URL in a single test step.
You can chain assertions like cy.url().should('include', '/account').and('match', /\?tab=.+/).and('not.include', 'error'). This checks the URL contains '/account', has a query parameter 'tab', and does not contain 'error'.
Result
Tests become more expressive and concise by combining multiple URL checks.
Chaining assertions improves test readability and covers multiple URL aspects efficiently.
5
AdvancedHandling asynchronous URL changes
🤔Before reading on: do you think cy.url() assertions automatically wait for URL changes? Commit to yes or no.
Concept: Understand how Cypress waits for URL changes and how to handle timing issues in tests.
Cypress automatically retries cy.url() assertions until they pass or timeout. This means if navigation takes time, cy.url().should('include', '/dashboard') waits until the URL updates. However, if the URL never changes, the test fails after timeout. You can adjust timeout with options.
Result
Tests reliably wait for navigation without manual delays.
Knowing Cypress's automatic waiting prevents flaky tests and unnecessary waits.
6
ExpertCustom URL assertion commands
🤔Before reading on: can you create your own Cypress command to assert URLs? Commit to yes or no.
Concept: Learn to write reusable custom commands for complex or repeated URL assertions.
You can add custom commands in Cypress like Cypress.Commands.add('assertUrlContains', (text) => { cy.url().should('include', text) }). Then use cy.assertUrlContains('/profile') in tests. This improves code reuse and clarity in large test suites.
Result
Your tests become cleaner and easier to maintain with custom URL assertions.
Creating custom commands leverages Cypress's extensibility for scalable testing.
Under the Hood
cy.url() works by accessing the browser's window.location.href property through Cypress's automation layer. When called, it fetches the current URL string from the browser context and returns it wrapped in a Cypress chainable object. Assertions on cy.url() use Cypress's retry-ability feature, which repeatedly checks the condition until it passes or times out, handling asynchronous navigation smoothly.
Why designed this way?
Cypress was designed to control the browser directly and provide automatic waiting to reduce flaky tests. Accessing URL via window.location.href is simple and reliable. The retry mechanism was chosen to handle dynamic web apps where navigation and URL changes happen asynchronously, avoiding manual waits or sleeps.
┌───────────────┐
│ Test Calls    │
│ cy.url()     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Cypress       │
│ Automation    │
│ Layer         │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Browser       │
│ window.location.href
│ (Current URL) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Returns URL   │
│ to Cypress    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Assertion     │
│ Retries until │
│ Pass or Fail  │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does cy.url() assertion immediately fail if the URL is not yet updated? Commit to yes or no.
Common Belief:Many think cy.url() assertions check the URL only once and fail immediately if it doesn't match.
Tap to reveal reality
Reality:Cypress automatically retries cy.url() assertions until the condition passes or a timeout occurs, allowing for asynchronous URL changes.
Why it matters:Believing it fails immediately leads to adding unnecessary waits or flaky tests that fail when navigation is slow.
Quick: Can cy.url() assertions check parts of the URL like query parameters directly? Commit to yes or no.
Common Belief:Some assume cy.url() can directly assert specific URL parts like query parameters without parsing.
Tap to reveal reality
Reality:cy.url() returns the full URL string; to check parts like query parameters, you must parse the URL or use string/regex assertions.
Why it matters:Misunderstanding this causes incorrect assertions or missed bugs in URL parameters.
Quick: Does cy.url() assertion change the browser URL? Commit to yes or no.
Common Belief:Some believe cy.url() can modify or set the browser URL during tests.
Tap to reveal reality
Reality:cy.url() only reads the current URL; it does not change or navigate the browser.
Why it matters:Confusing reading with navigation leads to wrong test designs and unexpected failures.
Quick: Can you use cy.url() assertions to test URLs in multiple tabs or windows? Commit to yes or no.
Common Belief:Many think cy.url() works across multiple browser tabs or windows.
Tap to reveal reality
Reality:Cypress runs tests in a single browser context and cannot switch tabs; cy.url() only checks the current tab's URL.
Why it matters:Expecting multi-tab support causes test failures and confusion about Cypress's capabilities.
Expert Zone
1
cy.url() assertions benefit from Cypress's automatic retry, but understanding the default timeout and how to customize it is crucial for flaky network conditions.
2
When testing apps with client-side routing (like React Router), the URL may change without full page reloads, so cy.url() assertions must consider timing carefully.
3
Custom commands wrapping cy.url() assertions can include logging or error handling to improve test diagnostics in large suites.
When NOT to use
Avoid relying solely on cy.url() assertions for verifying page content or state; use DOM element checks or API responses instead. For multi-tab or multi-origin tests, Cypress is limited; consider other tools or manual testing.
Production Patterns
In real projects, cy.url() assertions are combined with element checks to confirm navigation success. Teams create reusable custom commands for common URL patterns and integrate URL assertions in end-to-end workflows to catch navigation regressions early.
Connections
Stateful Web Navigation
cy.url() assertions build on the concept of tracking navigation state in web apps.
Understanding how web apps manage navigation state helps in writing precise URL assertions that reflect user journeys.
Regular Expressions
cy.url() assertions often use regex to match dynamic URL patterns.
Mastering regex empowers testers to write flexible URL checks that handle variable parts like IDs or tokens.
Quality Control in Manufacturing
Both cy.url() assertions and manufacturing quality checks verify that a product meets expected standards before moving forward.
Seeing URL assertions as quality gates helps appreciate their role in preventing defects from reaching users.
Common Pitfalls
#1Failing tests due to timing issues when URL changes are delayed.
Wrong approach:cy.url().should('eq', 'https://example.com/dashboard')
Correct approach:cy.url({ timeout: 10000 }).should('eq', 'https://example.com/dashboard')
Root cause:Not accounting for asynchronous navigation delays causes premature assertion failures.
#2Checking URL parts without parsing, leading to false positives.
Wrong approach:cy.url().should('include', 'tab=profile')
Correct approach:cy.url().then(url => { const params = new URL(url).searchParams; expect(params.get('tab')).to.equal('profile') })
Root cause:Treating URL as plain string without parsing query parameters causes unreliable tests.
#3Using cy.url() to try to navigate or change pages.
Wrong approach:cy.url('https://example.com/login')
Correct approach:cy.visit('https://example.com/login')
Root cause:Confusing cy.url() (getter) with navigation commands leads to test errors.
Key Takeaways
cy.url() assertions let you check the browser's current URL to confirm correct navigation during tests.
Cypress automatically retries URL assertions, making tests reliable even with asynchronous page loads.
You can use exact matches, partial includes, or regular expressions to flexibly verify URLs.
Custom commands improve test clarity and reuse when asserting URLs in complex applications.
Understanding cy.url() limitations, like single-tab scope and string-based URL checks, prevents common test mistakes.

Practice

(1/5)
1. What does cy.url().should('include', '/dashboard') check in a Cypress test?
easy
A. It checks if the current URL contains '/dashboard' anywhere in it.
B. It verifies the URL exactly equals '/dashboard'.
C. It asserts the URL starts with '/dashboard'.
D. It confirms the URL ends with '/dashboard'.

Solution

  1. Step 1: Understand the 'include' assertion

    The 'include' assertion checks if the given string is part of the actual URL anywhere.
  2. Step 2: Apply to the example

    Using 'include' with '/dashboard' means the URL must contain '/dashboard' anywhere, not necessarily exactly or at start/end.
  3. Final Answer:

    It checks if the current URL contains '/dashboard' anywhere in it. -> Option A
  4. Quick Check:

    cy.url().should('include', '/dashboard') = contains '/dashboard' [OK]
Hint: Remember 'include' means substring anywhere in URL [OK]
Common Mistakes:
  • Confusing 'include' with exact match
  • Thinking 'include' checks start or end only
  • Using 'eq' when 'include' is needed
2. Which of the following is the correct syntax to assert the URL exactly equals 'https://example.com/home' in Cypress?
easy
A. cy.url().should('contain', 'https://example.com/home')
B. cy.url().should('include', 'https://example.com/home')
C. cy.url().should('match', 'https://example.com/home')
D. cy.url().should('eq', 'https://example.com/home')

Solution

  1. Step 1: Identify exact match assertion

    The 'eq' assertion checks if the actual URL exactly equals the given string.
  2. Step 2: Match syntax to requirement

    Using cy.url().should('eq', 'https://example.com/home') asserts the URL is exactly that string.
  3. Final Answer:

    cy.url().should('eq', 'https://example.com/home') -> Option D
  4. Quick Check:

    Exact URL match uses 'eq' [OK]
Hint: Use 'eq' for exact URL match, not 'include' or 'match' [OK]
Common Mistakes:
  • Using 'include' instead of 'eq' for exact match
  • Using 'match' without regex
  • Using 'contain' which is not a valid Cypress assertion
3. Given the code snippet:
cy.visit('/login')
cy.url().should('match', /\/login$/)

What will the assertion check?
medium
A. The URL contains '/login' anywhere.
B. The URL ends with '/login'.
C. The URL exactly equals '/login'.
D. The URL starts with '/login'.

Solution

  1. Step 1: Understand the 'match' assertion with regex

    The 'match' assertion checks if the URL matches the given regular expression.
  2. Step 2: Analyze the regex /\/login$/

    The regex ends with '$' which means the URL must end with '/login'.
  3. Final Answer:

    The URL ends with '/login'. -> Option B
  4. Quick Check:

    Regex with $ means URL ends with pattern [OK]
Hint: Regex ending with $ means URL ends with that string [OK]
Common Mistakes:
  • Thinking 'match' checks substring anywhere without regex
  • Confusing regex anchors like ^ and $
  • Assuming 'match' equals exact string match
4. Identify the error in this Cypress assertion:
cy.url().should('equals', 'https://example.com/home')
medium
A. 'equals' is not a valid assertion keyword in Cypress.
B. The URL string is missing a trailing slash.
C. The method 'should' cannot be used with 'url'.
D. The URL must be checked with 'include' instead of 'equals'.

Solution

  1. Step 1: Check valid assertion keywords for cy.url()

    Cypress supports 'eq', 'include', 'match', but not 'equals'.
  2. Step 2: Identify the invalid keyword usage

    Using 'equals' causes a syntax error because it's not recognized by Cypress.
  3. Final Answer:

    'equals' is not a valid assertion keyword in Cypress. -> Option A
  4. Quick Check:

    Use 'eq' for exact match, not 'equals' [OK]
Hint: Use 'eq' not 'equals' for exact URL check [OK]
Common Mistakes:
  • Using 'equals' instead of 'eq'
  • Confusing assertion keywords
  • Assuming 'should' can't be chained with 'url'
5. You want to verify that after login, the URL contains '/dashboard' but may have query parameters like '?user=123'. Which assertion is best to use?
hard
A. cy.url().should('eq', 'https://example.com/dashboard')
B. cy.url().should('contain', '/dashboard?user=123')
C. cy.url().should('include', '/dashboard')
D. cy.url().should('match', /^https:\/\/example\.com\/dashboard\?user=\d+$/)

Solution

  1. Step 1: Understand the URL with query parameters

    The URL may have extra parts after '/dashboard', so exact match ('eq') won't work.
  2. Step 2: Choose assertion allowing partial match

    'include' checks if '/dashboard' is anywhere in the URL, ignoring query parameters.
  3. Final Answer:

    cy.url().should('include', '/dashboard') -> Option C
  4. Quick Check:

    Use 'include' to ignore query parameters [OK]
Hint: Use 'include' to ignore query parameters in URL check [OK]
Common Mistakes:
  • Using 'eq' which fails with query parameters
  • Trying complex regex without need
  • Using invalid 'contain' assertion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard