0
0
Cypresstesting~15 mins

cy.visit() for page navigation in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - cy.visit() for page navigation
What is it?
cy.visit() is a command in Cypress used to open a web page by navigating to a specified URL. It tells the browser to load the page you want to test. This is the first step in many tests to start from a known page. It works like typing a web address in your browser's address bar.
Why it matters
Without cy.visit(), tests would not know which page to start on, making it impossible to check if a website works correctly. It solves the problem of setting the starting point for tests automatically. Without it, testers would have to manually open pages, which is slow and error-prone. This command makes tests fast, repeatable, and reliable.
Where it fits
Before learning cy.visit(), you should understand basic web concepts like URLs and browsers. After mastering cy.visit(), you can learn how to interact with page elements and write assertions to check page content. It fits early in the Cypress testing journey as the foundation for navigation.
Mental Model
Core Idea
cy.visit() tells the browser to go to a specific web page so tests can start from there.
Think of it like...
It's like entering an address into a GPS before starting a trip; you need to tell it where to go first.
┌───────────────┐
│ Test Script   │
│ calls cy.visit()│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Browser       │
│ loads URL     │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Web Page      │
│ is displayed  │
└───────────────┘
Build-Up - 6 Steps
1
FoundationBasic usage of cy.visit()
🤔
Concept: Learn how to use cy.visit() to open a web page by URL.
In Cypress, you write cy.visit('https://example.com') to open that page. This command waits until the page fully loads before moving on. Example: cy.visit('https://example.com') This tells Cypress to open the example.com homepage.
Result
The browser opens https://example.com and the page is ready for testing.
Understanding how to open a page is the first step to testing any website with Cypress.
2
FoundationVisiting relative URLs
🤔
Concept: Use cy.visit() with relative paths based on the baseUrl setting.
If you set a baseUrl in Cypress config, you can visit pages by relative paths like cy.visit('/login'). Cypress combines baseUrl and the path to form the full URL. Example: // cypress.config.js // baseUrl: 'https://example.com' cy.visit('/login') This opens https://example.com/login.
Result
The browser opens the login page relative to the base URL.
Using relative URLs makes tests easier to maintain and run in different environments.
3
IntermediateHandling page load timing
🤔Before reading on: do you think cy.visit() waits for all page resources like images and scripts before continuing? Commit to your answer.
Concept: cy.visit() waits for the page's 'load' event but not necessarily all asynchronous requests.
cy.visit() waits until the browser fires the 'load' event, meaning the main HTML and resources are loaded. However, it does not wait for background API calls or animations. You may need extra commands to wait for those. Example: cy.visit('/dashboard') cy.get('.loading-spinner').should('not.exist') This waits for the page load and then waits for a spinner to disappear.
Result
Tests proceed only after the main page is loaded, but you control waiting for dynamic content.
Knowing what cy.visit() waits for helps avoid flaky tests caused by incomplete page loading.
4
IntermediatePassing options to cy.visit()
🤔Before reading on: do you think cy.visit() can send extra data like headers or authentication info? Commit to your answer.
Concept: cy.visit() accepts options to customize the request, like headers or authentication.
You can pass an options object as the second argument to cy.visit(). For example, to add headers: cy.visit('/profile', { headers: { 'Authorization': 'Bearer token123' } }) This sends the header with the page request. You can also control timeout and onBeforeLoad callbacks.
Result
The page loads with custom request settings, useful for testing protected pages.
Customizing cy.visit() requests allows testing scenarios like logged-in users or special headers.
5
Advancedcy.visit() with onBeforeLoad callback
🤔Before reading on: do you think you can run code inside the page before it loads fully using cy.visit()? Commit to your answer.
Concept: You can run JavaScript inside the page before it finishes loading using onBeforeLoad option.
The onBeforeLoad callback runs before the page's scripts start. You can use it to stub functions or set window properties. Example: cy.visit('/app', { onBeforeLoad(win) { win.localStorage.setItem('token', 'abc123') } }) This sets localStorage before the page scripts run.
Result
The page loads with the desired state already set, enabling tests of logged-in or customized states.
Manipulating the page environment before load helps test complex scenarios without manual steps.
6
Expertcy.visit() and Single Page Applications (SPA)
🤔Before reading on: do you think cy.visit() reloads the entire page every time in SPAs? Commit to your answer.
Concept: In SPAs, cy.visit() reloads the full page, but navigation inside the app uses client-side routing without reloads.
SPAs load once and then change views without full reloads. cy.visit() forces a full reload to reset state. Example: cy.visit('/dashboard') // full reload cy.get('nav').contains('Settings').click() // client-side route change Understanding this helps write tests that reset state properly and avoid false positives.
Result
Tests start fresh with cy.visit(), but can simulate user navigation inside the SPA without reloads.
Knowing how cy.visit() interacts with SPA routing prevents flaky tests and improves test speed.
Under the Hood
cy.visit() sends a command to the Cypress test runner to instruct the browser to load the specified URL. The browser navigates to the URL, triggering the HTTP request and loading the page. Cypress listens for the 'load' event signaling the page is ready. Internally, Cypress manages network interception and synchronization to ensure commands run only after the page is stable.
Why designed this way?
cy.visit() was designed to mimic real user navigation by loading pages in a real browser environment. This ensures tests reflect actual user experience. Waiting for the 'load' event balances speed and reliability, avoiding waiting too long for dynamic content that may never finish loading. The design supports flexibility with options for headers and callbacks to cover diverse testing needs.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Test Script   │──────▶│ Cypress Core  │──────▶│ Browser       │
│ calls cy.visit()│      │ sends command │       │ loads URL     │
└───────────────┘       └───────────────┘       └──────┬────────┘
                                                      │
                                                      ▼
                                             ┌───────────────┐
                                             │ Page Load     │
                                             │ 'load' event  │
                                             └───────────────┘
Myth Busters - 3 Common Misconceptions
Quick: Does cy.visit() wait for all API calls on the page to finish before continuing? Commit to yes or no.
Common Belief:cy.visit() waits for every network request on the page to complete before moving on.
Tap to reveal reality
Reality:cy.visit() only waits for the browser's 'load' event, not for all background API calls or dynamic content to finish loading.
Why it matters:Assuming cy.visit() waits for all requests can cause tests to run too early, leading to flaky failures when dynamic content is not ready.
Quick: Can you use cy.visit() to navigate within a Single Page Application without reloading the page? Commit to yes or no.
Common Belief:cy.visit() can navigate inside an SPA without reloading the entire page.
Tap to reveal reality
Reality:cy.visit() always reloads the full page; SPA internal navigation uses other commands like clicking links or invoking client-side routing.
Why it matters:Misusing cy.visit() for SPA navigation slows tests and resets state unnecessarily, causing inefficient and unreliable tests.
Quick: Does cy.visit() automatically handle authentication for protected pages? Commit to yes or no.
Common Belief:cy.visit() automatically logs in users or handles authentication when visiting protected pages.
Tap to reveal reality
Reality:cy.visit() does not handle authentication by itself; you must set cookies, headers, or localStorage before visiting or use login commands.
Why it matters:Expecting automatic login causes tests to fail on protected pages, confusing beginners about test failures.
Expert Zone
1
cy.visit() triggers a full page reload which resets all JavaScript state, so tests relying on persistent state must set it up again after visiting.
2
Using onBeforeLoad allows intercepting and modifying the window object before any page scripts run, enabling advanced stubbing and environment setup.
3
Passing custom headers or authentication tokens via cy.visit() options can simulate complex user scenarios without manual login flows.
When NOT to use
Avoid using cy.visit() for navigation inside Single Page Applications after the initial load; instead, simulate user clicks or use client-side routing commands to keep tests fast and stateful.
Production Patterns
In real-world tests, cy.visit() is used at the start of each test to ensure a clean slate. Experts combine it with onBeforeLoad to set authentication tokens or mock APIs. They avoid overusing cy.visit() to keep tests efficient, especially in SPAs.
Connections
HTTP Requests
cy.visit() triggers an HTTP GET request to load the page URL.
Understanding HTTP requests helps grasp what happens when cy.visit() loads a page and why network issues affect tests.
Event Loop in JavaScript
cy.visit() waits for the 'load' event, which is part of the browser's event lifecycle.
Knowing the event loop clarifies why cy.visit() waits for certain events and how asynchronous page loading affects test timing.
GPS Navigation
Both cy.visit() and GPS navigation require specifying a destination before starting the journey.
This cross-domain connection highlights the importance of setting a clear starting point before proceeding, a principle common in many systems.
Common Pitfalls
#1Starting tests without cy.visit() causes tests to run on the wrong page.
Wrong approach:cy.get('button').click() // without cy.visit() first
Correct approach:cy.visit('https://example.com') cy.get('button').click()
Root cause:Forgetting to navigate to the correct page means the test commands run on whatever page the browser currently shows, causing failures.
#2Using cy.visit() repeatedly inside a test to navigate inside an SPA slows tests and resets state.
Wrong approach:cy.visit('/dashboard') cy.visit('/settings')
Correct approach:cy.visit('/dashboard') cy.get('nav').contains('Settings').click()
Root cause:Misunderstanding SPA navigation causes unnecessary full page reloads, making tests slower and less realistic.
#3Assuming cy.visit() waits for all dynamic content causes flaky tests.
Wrong approach:cy.visit('/profile') cy.get('.user-name').should('contain', 'Alice') // immediately after visit
Correct approach:cy.visit('/profile') cy.get('.loading-spinner').should('not.exist') cy.get('.user-name').should('contain', 'Alice')
Root cause:Not waiting for dynamic content to load means assertions run too early, causing intermittent failures.
Key Takeaways
cy.visit() is the command to open a web page in Cypress tests, setting the starting point for testing.
It waits for the browser's 'load' event but not for all dynamic content, so additional waits may be needed.
Using relative URLs with baseUrl makes tests easier to maintain across environments.
Advanced options like onBeforeLoad let you prepare the page environment before scripts run.
In Single Page Applications, use cy.visit() only to load the initial page; use other commands for internal navigation.