Back to Resources

Blog

Posted August 11, 2023

Improve Your End To End Testing With Cypress

Learn how to do end-to-end testing in Cypress on a ReactJS application and Sauce Labs.

You know testing is crucial, but do you have confidence in your web application? Sure, your unit and integration tests cover a lot, but what about the actual user experience from end to end? End-to-end testing with Cypress is a game changer. Cypress is a next-generation, front-end testing tool built for the modern web. It lets you test anything that runs in a browser – and it’s fast, easy to set up, and open source.

Keep reading this article to learn how to do end-to-end testing in Cypress on a ReactJS application and Sauce Labs. 

What is Cypress?

Cypress is an open-source, end-to-end testing framework for web applications. It allows you to write automated tests that validate the functionality of your app from start to finish.

With Cypress, you can:

  • Perform cross-browser testing. Cypress supports the Chrome, Firefox, and Electron browsers.

  • Travel through time. Cypress enables you to take screenshots and videos of your tests. This makes debugging failures and reviewing test runs a breeze.

  • Write tests in JavaScript. If you're a front-end developer, you're already familiar with the language Cypress uses. No context switching is required!

  • Test asynchronous behavior. Cypress handles waiting for elements and network requests so you don't have to. Your tests will be clean and robust.

  • View test results in real time. The Cypress Test Runner shows you live previews of your app as it's being tested.

  • Run tests locally or in CI. Cypress integrates with popular CI providers like CircleCI, Travis CI, Jenkins, and more. 

Put simply, Cypress takes the pain out of end-to-end testing. With its simple yet powerful API, clean syntax, and interactive Test Runner, adding automated testing to your web application has never been easier.

Why Perform End-to-End Testing with Cypress?

Cypress is a front-end testing tool built for the modern web. It lets you write automated tests for anything that runs in a browser. Compared to other end-to-end testing tools like Selenium, Cypress provides a faster, easier, and more reliable testing experience.

Some of the main benefits of end-to-end testing with Cypress are:

  • It'ss fast. Cypress runs tests directly in the browser, not on a separate server. This results in much faster test runs.

  • It is easy to set up. You don't need to install any plugins or drivers. Just install the Cypress package and you're ready to write your first test.

  • It has a simple API. Cypress has clear, readable syntax and intuitive, chainable commands. Writing tests is simple and fun!

  • It takes snapshots. Cypress automatically takes snapshots of failures, so you have a visual diff of what went wrong. No more guessing why your test failed.

  • It has built-in support for time travel. You can go back in time to see the exact state of your application at any point. This makes debugging much easier.

  • It works with any front-end framework. Cypress supports React, Vue.js, Angular, and more. You're not locked into any specific stack.

  • It has a robust ecosystem. Cypress has a large community building open-source plugins, examples, and tooling to extend its functionality.

Overall, Cypress makes end-to-end testing delightful. By removing many of the headaches traditionally associated with end-to-end testing, Cypress allows you to build a robust test suite and gain confidence in your application.

How to Perform End-to-End Testing with Cypress and Sauce Labs

Cypress is an open-source testing tool that lets you write and run end-to-end tests for web applications. Cypress and Sauce Labs together provide an ideal combination for running fast, reliable end-to-end tests at scale. To show Cypress in action, we'll walk through an example using Sauce Labs, a cloud-based web and mobile testing platform.

Before anything else, we need an existing application to test. In this case, we’ll use a sample web application built using ReactJS via GitHub

This is how it looks: 

We will focus on testing the navigation via different routes, authentication, and image loading. Let’s go ahead and get started.

1. Set up Cypress

To get started, install Cypress locally using npm:

npm install cypress

After installation, the cypress directory should look like this: 

Cypress directory

Let’s break down the folder structure:

└── cypress/

    ├── fixtures/            // This folder stores test data and mock responses

    ├── integration/         // Contains the actual test files

    ├── plugins/             // Stores any custom plugins you create with Cypress

    ├── support/             // Stores any shared files (utility functions & reusable test commands) 

    ├── screenshots/         // Automatically stores any screenshots taken during test runs

    └── videos/              // Automatically stores any videos recorded during test runs

Next, initialize Cypress:

npx cypress open

This will open the Cypress app, where you can see and run tests, configure settings, and more.

Cypress app

2. Writing Cypress tests

Cypress tests are written in JavaScript and executed in the browser. Create your first test in cypress/integration/gallery-app.spec.js:

1
describe('Gallery App', () => {
2
    beforeEach(() => {
3
      cy.visit('http://localhost.com');
4
    });
5
    it('should display the home page', () => {
6
      cy.contains('Welcome to the Gallery App').should('be.visible');
7
    });
8
    it('should navigate to Sign In page', () => {
9
      cy.contains('Sign In').click();
10
      cy.url().should('include', '/sigCnin');
11
    });
12
    it('should navigate to Sign Up page', () => {
13
      cy.contains('Sign Up').click();
14
      cy.url().should('include', '/signup');
15
    });
16
    it('should navigate to Gallery page', () => {
17
      cy.contains('Gallery').click();
18
      cy.url().should('include', '/gallery');
19
    });
20
  });

The above tests simply check the application navigation to several routes within the Gallery-App application. After this, you run the tests via Cypress by running the following command in your terminal: 

$ ./node_modules/.bin/cypress open

Running Cypress tests on Sauce Labs

To run Cypress tests on Sauce Labs, you'll need to:

  1. Create a Sauce Labs account and get your username/access key.

  2. Set the CYPRESS_BASE_URL environment variable to https://{username}:{accessKey}@ondemand.saucelabs.com/wd/hub.

  3. Set the CYPRESS_VIDEO_COMPRESSION environment variable to true.

  4. Add the sauce object to your cypress.json config.

Once you’ve finished the above, the cypress.json file should look like this: 

{

"base

Url": "https://{username}:{accessKey}@ondemand.saucelabs.com/wd/hub",

"env": {

"CYPRESS_VIDEO_COMPRESSION": "true",

"sauce": {

"username": "your_saucelabs_username",

"accessKey": "your_saucelabs_accesskey"

   }

}

}

Be sure to replace the username and accessKey with your actual Sauce Labs account credentials. 

Now you can run your final Cypress tests, and they will execute on Sauce Labs: 

$ ./node_modules/.bin/cypress open

The final results (with all 4 tests passing) look like this:

Cypress test results

When the Cypress tests finish running, new files (screenshots and videos) will be appended on your directory as a record of your tests. This ability to keep track of your tests is one of the key benefits of using Cypress for E2E testing.

Cypress directory with files appended

The complete code can be found on this GitHub repository

Cypress Features For Better E2E Testing

Cypress has powerful features that make end-to-end testing a breeze, simplify the testing process, and provide unparalleled reliability and speed. These features help teams deliver high-quality software with confidence.

Time travel

Cypress lets you go back in time to the previous state of your application. If a test fails, you can go back to when the application was working properly to debug what went wrong. This “time travel debugging” allows you to step through the commands that were run during the test to pinpoint the cause of the failure.

Automatic waiting

Cypress automatically waits for commands and assertions before moving on. It will wait for elements to become visible, animations to complete, and XHR requests to finish. This means you don’t have to add arbitrary waits and sleeps in your tests. Cypress handles waiting for you so your tests remain stable.

Debuggability

Cypress has a robust debugger that allows you to step through commands, see their outputs, and visually inspect your application at any point. You can place debug statements, use browser developer tools, and set breakpoints to gain insight into your application. The Cypress Dashboard also provides screenshots, videos, command logs, and more to help you understand exactly what your tests are doing.

Cross-browser testing

Cypress supports Chrome, Firefox, and Electron out of the box. You can also configure Cypress to run on Safari. This means you can write tests once and run them across multiple browsers to ensure that your application works as expected for all your users.

Dashboard service

The Cypress Dashboard is a service that provides analytics for your tests across builds and runs. It gives you insights into the health of your tests, shows failures, automatically retries unstable tests, and much more. The Dashboard aims to provide an overview of your testing to help optimize your development workflows.

Open source

Cypress is free and open source, backed by a thriving community of contributors, and maintained by Cypress.io. You can download, modify, and distribute Cypress for nearly any purpose. The open nature of Cypress means that you have complete control over and visibility into your testing toolchain.

Cypress Challenges

Cypress end-to-end testing does come with some challenges you'll need to be aware of, including the following:

One issue is flaky tests. Because Cypress runs tests against a real browser, unstable network connections or heavy server loads can sometimes cause tests to fail intermittently through no fault of your own.

In addition, Cypress can't handle every browser. While it supports Chrome, Firefox, and Edge, it lacks support for Safari and older browsers.

Visual regression testing requires extra setup. Cypress can do basic style and layout checks, but for full visual regression testing, you'll need to integrate a service like Percy or Applitools. This requires additional configuration and expense.

Tests can be slow to run. Cypress tests run slower than unit tests because they spin up a real browser and website. As your test suites grow, the total runtime can become quite long. You'll need to find ways to speed up your tests, like running them in parallel or stubbing out slow API responses.

Finally, Cypress has limited debugging tools. While Cypress does have some built-in debugging ability, it can still be difficult to step through and debug failed tests. You may need to rely more heavily on console logs, breakpoints, and the browser's native debugging tools.

5 Best Practices for Cypress End-to-End Testing

Once you’ve set up Cypress, it’s time to start writing tests. Here are some best practices to keep in mind:

1. Keep tests independent

Each test should focus on one piece of functionality and not depend on other tests. This makes debugging easier and allows tests to run in any order.

2. Use page objects

Page objects contain the selectors and methods for interacting with a page. They keep your tests DRY (Don’t Repeat Yourself) and maintainable. If the UI changes, you only have to update the page object. 

3. Keep tests short

Each test should focus on one scenario. Don’t cram too many assertions or interactions into a single test. Short, simple tests are easier to debug and maintain.

4. Add comments

Add comments describing the purpose of sections in your tests. This helps anyone reading the tests understand what's being tested.

5. Review best practices often

Cypress testing best practices will evolve over time. Review them regularly to keep improving your end-to-end tests.

Making End To End Testing Better

Cypress end-to-end testing coupled with Sauce Labs offers a powerful solution for ensuring the reliability and efficiency of applications and software. By leveraging Cypress's robust testing framework and Sauce Labs' scalable cloud infrastructure, developers can seamlessly integrate testing into their CI/CD pipelines and accelerate the delivery of high-quality software. By mastering Cypress, teams can enhance test coverage and gain valuable insights into application performance across various browsers and devices. With Cypress and Sauce Labs, teams can confidently ship code, knowing that their applications are thoroughly tested and ready to meet the demands of users in today's dynamic digital landscape.

Get started testing with Cypress on Sauce Labs today!

Ready to start Cypress end-to-end testing with Sauce Labs?

Get started

© 2023 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are registered trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.