How to Use cy.visit in Cypress for Web Testing
Use
cy.visit(url) in Cypress to open a web page by providing its URL as a string. This command loads the page and waits for it to fully load before running further test steps.Syntax
The basic syntax of cy.visit is simple. You provide the URL of the page you want to open as a string. Optionally, you can pass an object with options like headers or query parameters.
url: The web address to visit, e.g.,'https://example.com'.options: Optional settings liketimeoutoronBeforeLoadcallback.
javascript
cy.visit(url, options)
Example
This example shows how to visit the Cypress official website and check that the page title contains 'Cypress'.
javascript
describe('Visit example page', () => { it('opens Cypress website and checks title', () => { cy.visit('https://www.cypress.io') cy.title().should('include', 'Cypress') }) })
Output
Test passes if the page loads and the title includes 'Cypress'.
Common Pitfalls
Common mistakes when using cy.visit include:
- Using a relative URL without setting
baseUrlincypress.config.js, which causes errors. - Not waiting for the page to load before running assertions, though
cy.visitwaits by default. - Passing incorrect URL strings or missing the protocol (http/https).
Always ensure URLs are correct and consider setting baseUrl for relative paths.
javascript
/* Wrong way: missing protocol */ cy.visit('www.example.com') // This will fail /* Right way: include protocol */ cy.visit('https://www.example.com')
Quick Reference
| Usage | Description |
|---|---|
| cy.visit('https://example.com') | Open the specified URL and wait for load |
| cy.visit('/login') | Visit relative URL if baseUrl is set in config |
| cy.visit('https://example.com', { timeout: 10000 }) | Set custom timeout for page load |
| cy.visit('https://example.com', { onBeforeLoad(win) { /* code */ } }) | Run code before page loads |
Key Takeaways
Use cy.visit(url) to open a web page during Cypress tests.
Always include the full URL or set baseUrl for relative paths.
cy.visit waits for the page to load before continuing tests.
Avoid missing protocols like http or https in URLs.
Use options to customize behavior like timeout or event hooks.