Back to Test Automation
2026-02-217 min read

Cypress Can Be Simple (Sometimes) (Test Automation)

Learn Cypress Can Be Simple (Sometimes) (Test Automation) step by step with clear examples and exercises.

Why This Matters

Automated testing is essential for ensuring the quality of web applications. Manual testing can be time-consuming and prone to human error, while automated tests allow developers to catch issues early in the development process, saving both time and resources. Cypress stands out among other test automation frameworks due to its simplicity, fast execution, real-time replay of tests, and robust feature set that makes it suitable for a wide range of testing scenarios.

Prerequisites

To follow along with this lesson, you'll need:

  1. Basic understanding of JavaScript (ES6 syntax) – Familiarity with modern JavaScript features like arrow functions, template literals, and destructuring assignment is necessary for writing Cypress tests effectively.
  2. Knowledge of HTML and CSS – Understanding the structure and styling of web pages is crucial when interacting with elements during test automation.
  3. Familiarity with Node.js and npm (Node Package Manager) – This includes understanding how to install, update, and manage dependencies for your project using npm.
  4. A text editor or Integrated Development Environment (IDE) like Visual Studio Code or Atom – These tools provide features such as syntax highlighting, code completion, and debugging that can make writing and testing Cypress tests more efficient.

Core Concept

Installation

To get started with Cypress, you'll first need to install it using npm:

npm install cypress --save-dev

This command will add Cypress as a development dependency in your project.

Test Files and Structure

Cypress tests are written in JavaScript files located within the cypress/integration directory of your project. Each test file is an individual test suite, and you can create subfolders to organize your tests based on features or pages.

my-project/
├── src/
│ ....
└── cypress/
├── integration/
│ ├── examples/
│ │ ├── example_test.js
│ │ └── ...
│ ├── login/
│ │ ├── login_test.js
│ │ └── ...
│ └── dashboard/
│ ├── dashboard_test.js
│ └── ...
└── support/
├── commands.js
└── ...

Writing Tests (Expanded)

Writing a Cypress test involves creating a new JavaScript file inside the cypress/integration directory and using the describe() function to group related tests together. Each test case is represented by the it() function, which takes a string describing the test and a callback function that contains the test code:

// cypress/integration/example.spec.js
describe('My First Test', () => {
it('Visits the Cypress website', () => {
// Your test code here
});

it('Fills out a form and submits it', () => {
// Your test code here
});
});

Interacting with Elements (Expanded)

Cypress provides several methods for interacting with elements on a webpage, such as cy.visit(), cy.get(), and cy.click(). Here's an example of visiting the Cypress website and clicking a button:

describe('My First Test', () => {
it('Visits the Cypress website and clicks a button', () => {
cy.visit('https://www.cypress.io/');
cy.get('#main-header').within(() => {
cy.contains('Get Started').click();
});
});
});

You can also use the type() function to fill out input fields, and the cy.url() function to verify that you're on the correct page:

describe('My First Test', () => {
it('Visits the Cypress website, fills out a form, and submits it', () => {
cy.visit('https://www.cypress.io/');
cy.get('#username').type('Test User');
cy.get('#email').type('test@example.com');
cy.get('#submit-button').click();
cy.url().should('include', '/thank-you'); // Verify that the correct page was reached
});
});

Assertions (Expanded)

Assertions are used to verify that the application behaves as expected. Cypress offers several assertion methods, such as cy.should(), cy.expect(), and cy.contains(). Here's an example of verifying that a specific text appears on the page:

describe('My First Test', () => {
it('Visits the Cypress website and checks for a specific text', () => {
cy.visit('https://www.cypress.io/');
cy.get('#main-header').within(() => {
cy.contains('Get Started'); // This line will pass if the text is found
});
});
});

You can also use cy.expect() to perform more complex assertions, such as checking the value of an input field:

describe('My First Test', () => {
it('Fills out a form with specific values', () => {
cy.visit('/'); // Replace with your application's URL

cy.get('#username').type('Test User');
cy.get('#email').type('test@example.com');

// Verify that the username and email fields have the correct values
cy.get('#username').should('have.value', 'Test User');
cy.get('#email').should('have.value', 'test@example.com');
});
});

Worked Example

Let's create a more complex test for a hypothetical web application. We'll visit the login page, fill out the form with valid credentials, and verify that we can successfully log in:

  1. Create a new file called login_test.js in the cypress/integration/login directory.
  2. Write the test code:
describe('Login Test', () => {
it('Logs in with valid credentials', () => {
cy.visit('/login'); // Replace with your application's login URL

// Find the input fields and fill them out
cy.get('#username').type('testuser');
cy.get('#password').type('secret1234');

// Click the login button
cy.get('#login-button').click();

// Verify that we're on the dashboard page
cy.url().should('include', '/dashboard');
});
});
  1. Run the test using the following command:
npx cypress run --spec "cypress/integration/login/login_test.js"

Common Mistakes

  1. Not waiting for elements to load: Always use cy.wait() or other methods like cy.get().should('exist') to ensure that elements are loaded before interacting with them. This can prevent errors caused by trying to access elements that haven't yet appeared on the page.
  1. Using cy.contains() with complex selectors: When using cy.contains(), try to make the selector as specific as possible to avoid matching unintended elements. This can help reduce false positives and make your tests more reliable.
  1. Not handling errors gracefully: If an error occurs during a test, it can cause the entire suite to fail. Use cy.try() and cy.catch() to handle errors more effectively, allowing you to isolate and address issues that arise during testing.
  1. Ignoring timeouts: Cypress tests run in a separate environment with timeouts for various operations like network requests and DOM manipulation. Be aware of these timeouts and adjust them as needed to ensure your tests have enough time to complete successfully.
  1. Not using beforeEach() and afterEach() hooks: These hooks allow you to set up shared resources before each test and clean up after each test, respectively. This can help improve the efficiency of your test suite by reducing duplicated setup and teardown code.

Practice Questions

  1. Write a test that verifies the login functionality of your application using Cypress. Consider handling errors gracefully and waiting for elements to load as needed.
  2. Create a test that checks the functionality of a search bar in your web application. Verify that the search results are displayed correctly when searching for different keywords.
  3. Write a test that validates the correct display of data in a table on your application's dashboard. Check that the table headers and rows are present, and that filtering and sorting functionality works as expected.
  4. Create a test that simulates user interactions with a carousel or slideshow on your web application. Verify that the correct slide is displayed after navigating through the carousel using next and previous buttons.

FAQ

  1. Why should I use Cypress instead of other test automation frameworks like Selenium or Playwright?
  • Cypress is designed to provide a better developer experience with faster execution times, real-time replay of tests, and easy debugging. It also offers modern APIs for interacting with the DOM and network requests, making it easier to write tests that closely mimic user interactions.
  1. How can I run my Cypress tests in multiple browsers?
  • By default, Cypress runs your tests in Chrome. To test in other browsers like Firefox or Safari, you'll need to configure the cypress.json file and install browser-specific plugins. This allows you to run your tests across different browsers and ensure compatibility with various browser environments.
  1. How can I handle asynchronous code in my Cypress tests?
  • Use the cy.wrap() function to wrap asynchronous functions or promises in a synchronous context, making them easier to work with in your tests. You can also use cy.then() to chain multiple asynchronous operations together and handle their results.
  1. How can I reuse test code across different tests?
  • Use custom commands defined in the support/commands.js file to create reusable functions that can be called from multiple tests. This promotes code organization and reduces duplication.
  1. How can I generate test reports or integrate Cypress with continuous integration (CI) tools?
  • Cypress provides several plugins for generating test reports, such as Mochawesome and Allure. You can also use Cypress's CLI options to integrate it with popular CI tools like Jenkins, CircleCI, and GitHub Actions. This allows you to run your tests automatically on each code commit and receive notifications of any test failures.
Cypress Can Be Simple (Sometimes) (Test Automation) | Test Automation | XQA Learn