Back to Test Automation
2025-12-237 min read

Cypress URLs (Test Automation)

Learn Cypress URLs (Test Automation) step by step with clear examples and exercises.

Why This Matters

In modern software development, test automation plays a crucial role in ensuring application quality and consistency across various environments. Tools like Selenium, Playwright, and Cypress have gained popularity due to their ease of use and powerful features. In this tutorial, we will focus on using Cypress for URL handling, which is essential when testing web applications that involve navigation between different pages or URLs.

Test automation not only saves time and resources but also helps catch regressions and ensure the consistency of your application across various environments. By mastering Cypress's capabilities for URL handling, you can create robust test suites that cover a wide range of scenarios, ultimately improving the overall quality of your web applications.

Prerequisites

To follow along with this tutorial, you need to have the following prerequisites in place:

  • Basic knowledge of JavaScript (ES6)
  • Familiarity with modern JavaScript concepts such as arrow functions, template literals, destructuring, and promises.
  • Node.js and npm installed on your machine
  • Ensure you have Node.js (version 12 or higher) and npm installed. You can check your versions by running node -v and npm -v in the terminal.
  • A text editor like Visual Studio Code or Atom
  • Choose a code editor that supports JavaScript, such as Visual Studio Code (VSCode) or Atom. These editors offer features like syntax highlighting, autocompletion, and debugging tools to help you write efficient test cases.
  • Familiarity with Cypress (installed globally using npm install cypress)
  • Make sure you have installed Cypress globally on your machine by running the command npm install cypress. This will allow you to use Cypress in your project.

Core Concept

Cypress provides various APIs to interact with the browser, including handling URLs. The primary API for navigating between URLs is the cy.visit() command, which opens a new browser tab or window and loads the specified URL.

cy.visit() (expanded)

The cy.visit() command takes a string argument representing the URL to be loaded. For example:

cy.visit('http://example.com');

By default, cy.visit() opens the URL in a new browser tab. However, you can specify options to control how the URL is loaded, such as setting the browser window size or clearing local storage.

Options (expanded)

To pass options to the cy.visit() command, use an object with key-value pairs as the second argument:

cy.visit('http://example.com', {
// Set browser window size
width: 1280,
height: 720,

// Clear local storage before visiting the URL
onBeforeLoad(window) {
window.localStorage.clear();
},
});

cy.url() and cy.location() (expanded)

After navigating to a URL using cy.visit(), you can retrieve the current URL or location details using the cy.url() and cy.location() commands, respectively. These commands return aliases that can be chained with other Cypress commands:

cy.visit('http://example.com');

// Get the current URL
const url = cy.url();
expect(url).to.equal('http://example.com');

// Get location details (e.g., hostname, port, pathname)
const location = cy.location();
expect(location.hostname).to.equal('example.com');

Worked Example

Let's create a simple test case that navigates to two different URLs and verifies the page titles:

  1. Install Cypress in your project by running npm install cypress.
  2. Create a new file named example_spec.js in the cypress/integration folder.
  3. Add the following code to example_spec.js:
describe('URL Navigation', function() {
it('visits and verifies page titles', function() {
// Visit the first URL and verify the page title
cy.visit('https://www.google.com');
cy.title().should('include', 'Google');

// Wait for the Google search bar to appear before typing a query
cy.get('#tsf > div:nth-child(2) > div > div > input[name="q"]')
.should('be.visible')
.type('Cypress Test Automation');

// Wait for the search results to load and verify the presence of a result title
cy.get('.yuRUbf a').first().should('have.text', 'Cypress - Wikipedia');

// Visit the second URL and verify the page title
cy.visit('https://www.wikipedia.org', {
width: 1280,
height: 720,
});
cy.title().should('include', 'Wikipedia');
});
});
  1. Run the test case by executing npm run cypress open.

In this example, we have expanded the test case to include waiting for specific elements to appear before interacting with them and verifying search results. This demonstrates how Cypress's APIs can help you create more robust test cases that handle asynchronous operations effectively.

Common Mistakes

  • Forgetting to import Cypress: Make sure you have imported Cypress at the beginning of your JavaScript file:
const { describe, it } = require('mocha');
const { expect } = require('chai');
import './support/commands';
import 'cypress';
  • Not using aliases for URLs: Avoid hardcoding URLs in your tests. Instead, create an alias for each URL to make your tests more readable and maintainable:
beforeEach(function() {
cy.server();
cy.route({ method: 'GET', url: '/api/*', response: {} });

// Define aliases for the URLs
cy.visit('https://example.com').as('homePage');
cy.visit('https://another-example.com').as('otherPage');
});
  • Not waiting for page load: Ensure that you wait for the page to load before interacting with its elements. Cypress provides various APIs for handling asynchronous operations, such as cy.wait() and cy.get().
  • ### Mistakes in cy.visit()
  • Incorrect URL syntax: Make sure your URLs are properly formatted, including the use of single or double quotes, and that they do not contain any typos.
  • Relative paths: Be aware that cy.visit() uses relative paths by default. If you want to navigate to an absolute URL, you can use the baseUrl configuration option in your Cypress config file (cypress.json) or set it dynamically during test execution:
// In your test file
const baseUrl = 'https://my-app.com';
Cypress.config('baseUrl', baseUrl);

cy.visit('/some-page'); // Now the URL will be 'https://my-app.com/some-page'

Practice Questions

  1. Write a test case that navigates to the Google search results page for the query "Cypress Test Automation" and verifies the presence of the search result title.
  • Solution:
describe('Google Search', function() {
it('searches for Cypress Test Automation', function() {
cy.visit('https://www.google.com');
cy.get('#tsf > div:nth-child(2) > div > div > input[name="q"]')
.type('Cypress Test Automation')
.type('{enter}');

// Wait for the search results to load and verify the presence of a result title
cy.get('.yuRUbf a').first().should('have.text', 'Cypress - Wikipedia');
});
});
  1. Create an alias for your project's homepage URL in your test suite.
  • Solution:
beforeEach(function() {
cy.server();
cy.route({ method: 'GET', url: '/api/*', response: {} });

// Define aliases for the URLs
cy.visit('https://example.com').as('homePage');
});
  1. Write a test case that navigates to a specific article on Wikipedia using the URL parameter (e.g., https://www.wikipedia.org/wiki/Test_automation) and verifies the title of the article.
  • Solution:
describe('Wikipedia Article', function() {
it('visits a specific article', function() {
cy.visit(Cypress.env('WIKIPEDIA_URL') + '/wiki/Test_automation');
cy.title().should('include', 'Test automation');
});
});
  • Note: You can set the WIKIPEDIA_URL environment variable in your Cypress configuration file (cypress.json) or by using the cy.env() command during test execution:
// In your test file
const wikipediaUrl = 'https://en.wikipedia.org';
cy.env('WIKIPEDIA_URL', wikipediaUrl);
  1. Write a test case that checks if a user can navigate from the homepage of your project to a specific subpage and back.
  • Solution:
describe('Navigation between pages', function() {
it('navigates to a subpage and back', function() {
// Visit the homepage
cy.visit('/');

// Click on the link to navigate to the subpage
cy.get('a[href="/subpage"]').click();

// Verify that we are on the subpage
cy.url().should('include', '/subpage');

// Navigate back to the homepage
cy.go('/');

// Verify that we are back on the homepage
cy.url().should('include', '/');
});
});

FAQ

  1. Why should I use Cypress for URL handling instead of other tools like Selenium or Playwright?

Cypress offers several advantages over other test automation tools, such as faster execution times due to in-memory testing, real-time reloading of the page during tests, and better support for modern JavaScript features. Additionally, Cypress provides a more user-friendly API for handling URLs compared to Selenium or Playwright.

  1. What are some best practices when using cy.visit()?

When using cy.visit(), make sure you wait for the page to load before interacting with its elements. You can use Cypress's APIs like cy.wait() and cy.get() to handle asynchronous operations effectively. Also, consider setting up aliases for your project's URLs to make your tests more readable and maintainable.

  1. How can I set the base URL for my Cypress tests?

You can set the base URL for your Cypress tests by either configuring it in your cypress.json file or setting it dynamically during test execution using the Cypress.config() function. This allows you to navigate to absolute URLs without having to specify them every time you use cy.visit().

  1. What are some common mistakes to avoid when working with Cypress and URL handling?

Some common mistakes include forgetting to import Cypress, not using aliases for URLs, not waiting for page load, and incorrect URL syntax. Be aware of these pitfalls to ensure your tests run smoothly and efficiently.

Cypress URLs (Test Automation) | Test Automation | XQA Learn