0
0
CypressHow-ToBeginner ยท 3 min read

How to Visit URL in Cypress: Simple Guide with Examples

In Cypress, you can visit a URL using the cy.visit() command by passing the URL string as an argument. This command loads the page in the test browser, allowing you to interact with it in your tests.
๐Ÿ“

Syntax

The basic syntax to visit a URL in Cypress is cy.visit(url). Here, url is a string representing the web address you want to open. You can use absolute URLs like 'https://example.com' or relative URLs if you have a baseUrl set in your Cypress configuration.

  • cy.visit(url): Opens the specified URL in the test browser.
  • url: A string URL to visit.
javascript
cy.visit('https://example.com')
๐Ÿ’ป

Example

This example shows how to visit a URL and check if the page contains a specific element. It demonstrates loading the page and making a simple assertion.

javascript
describe('Visit URL Example', () => {
  it('should open the homepage and check the title', () => {
    cy.visit('https://example.cypress.io')
    cy.contains('Kitchen Sink').should('be.visible')
  })
})
Output
Test passes if the page loads and the text 'Kitchen Sink' is visible.
โš ๏ธ

Common Pitfalls

Common mistakes when using cy.visit() include:

  • Using an incorrect or malformed URL string, which causes the test to fail to load the page.
  • Not waiting for the page to fully load before interacting with elements, leading to flaky tests.
  • Forgetting to set baseUrl in cypress.config.js and using relative URLs incorrectly.

Always ensure URLs are correct and use assertions to confirm page load.

javascript
/* Wrong way: Missing quotes around URL string */
// cy.visit(https://example.com) // This will cause a syntax error

/* Right way: Use quotes around URL string */
cy.visit('https://example.com')
๐Ÿ“Š

Quick Reference

Here is a quick cheat sheet for cy.visit() usage:

UsageDescription
cy.visit('https://example.com')Visit an absolute URL
cy.visit('/login')Visit a relative URL (requires baseUrl set)
cy.visit('https://example.com', { timeout: 10000 })Visit URL with custom timeout
cy.visit('https://example.com', { onLoad: (contentWindow) => { /* custom code */ } })Visit URL with event callback
โœ…

Key Takeaways

Use cy.visit(url) to open a web page in Cypress tests.
Always pass the URL as a string with quotes to avoid syntax errors.
Set baseUrl in Cypress config to use relative URLs easily.
Wait for page elements to load before interacting to avoid flaky tests.
Use assertions after cy.visit() to confirm the page loaded correctly.