0
0
CypressHow-ToBeginner ยท 3 min read

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 like timeout or onBeforeLoad callback.
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 baseUrl in cypress.config.js, which causes errors.
  • Not waiting for the page to load before running assertions, though cy.visit waits 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

UsageDescription
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.