Testing React App with Cypress

Published On: 11 August 2023.By .

What is Cypress?

It is a JavaScript-based testing framework built for the modern web.

Some features of Cypress are as follows:-

  1. Tests are executed in the browser enabling us to see what happens in our test with each step.
  2. Readable errors and stack traces make debugging lightning-fast.
  3. It supports automated waiting. Hence, it does not require async-await operations.
  4. It also includes the spies stub and clocks function gradually for mocking, modifying a function value and controlling the application’s date time.
  5. You can take screenshots or videos of your entire test suite when run from the CLI.
  6. You can test cross-browser testing simultaneously.

Setting Up Cypress in a ReactJS Project

  1. Install Cypress as a dev dependency using npm or yarn:
  2. Open Cypress test runner. Cypress Test Runner will open, allowing you to create and manage your tests. By default, a sample test spec file for you is generated to get started.
  3. In the opened window choose the testing type i.e. Component testing or E2E testing.Available testing types in cypress
  4. Now Cypress tells you some essential files are being added as a part of the setup in your applicationCypress configuration files
  5. Now select the browser you want to run the test cases in. Cypress automatically detects available browsers on your OS. You can switch the browser by using the drop-down near the top right corner. Examples:-Chrome, Electron, Firefox
  6. For creating a test file choose to create a new spec tab and after giving the path of the new spec the file is created in the Cypress folder with some basic code. (You can also create your testing file in your desired folder where the testing component is present.)Create your first spec

Types of Testing

In ReactJS, there are several types of testing that you can perform to ensure the quality and reliability of your application. Here are the most common types of testing in ReactJS:

  1. Unit Testing: Unit tests focus on testing individual units or components of your React application in isolation. In React, this typically involves testing individual React components and their functionalities.
  2. Integration Testing: Integration tests examine how different components in your React application work together. They test the interaction and integration between various components to ensure that they function correctly as a whole. 
  3. Component Testing: Component testing focuses on testing React components’ behaviour, rendering, and interactions with users. It ensures that components render correctly, respond appropriately to user input, and maintain the desired state.
  4. Snapshot Testing: Snapshot testing captures the rendered output of a component and compares it to a stored snapshot. It helps detect unintended changes in the component’s appearance or structure. 
  5. End-to-End (E2E) Testing: E2E testing aims to simulate real user scenarios and interactions with your React application. It tests the entire application flow from start to finish, including multiple components, APIs, and external dependencies. 

Out of the above options Cypress has 2 types of testing:- Component Testing and E2E Testing

E2E Testing vs Component  Testing

  1. The primary difference is that with E2E testing you visit a webserver with cy.visit() whereas in component testing, you mount your component directly with cy.mount().
  2. In Component testing, we mount an element or component and test its UI and events i.e. Unit and Integration testing whereas in E2E testing we can test our project flow i.e. Unit and Integration Testing.
  3. In E2E testing we have to run npm start as well because it loads the URL in cy.visit() from that whereas in component testing it’s not required to do so.
  4. In Cypress, E2E testing and component testing share the same driver, server and commands.

Writing Cypress Tests for ReactJS

Test block flow

  1.  Mounting a component

    1. Test block in Cypress Component Testing

      1. In Cypress, for mounting a component we use cy.mount(<Component />).
      2. Since our component is wrapped in a different HOC(Higher Order Component) so instead of directly mounting the component we wrapped the component in HOC that we used in our app originally. Now we render the component like this:
    2. Test block in Cypress E2E Testing

      1. To add the base URL of the page URLs add it to the Cypress config file(cypress.config.ts or cypress.config.js) and relaunch the Cypress window. Command:
      2.  The cy.visit() command helps you visit a remote URL.
  2.  Find, Interact and Assert 

    • Cypress offers various methods to find elements on the screen like cy.contains(), cy.get(), etc.
      • cy.get() gets one or more DOM elements while cy.contains() gets only one DOM element.
    • For assertion on the yielded subject, we use the cy.should() method. This method allows us to give a message we would like to assert.
    • To interact with elements like typing in text fields, and clicking on buttons we use Action API from Cypress.
    1.  Intercepting APIs and stubbing in Cypress

      • We can intercept APIs, their responses and other things as we want them to be for our test cases using cy.intercept(), cy.fixture() etc.
      • Stubbing replaces a function, records its usage and controls its behaviour.
        • cy.stub() is synchronous and returns the value (The stub) instead of a promise-like object. It can be aliased.

    2.   Cache the session in Cypress E2E

      • To avoid logging in for every test suite we can create a session in Cypress to cache and restore cookies, local storage and session storage data.
      • The web storage can be accessed while testing as usual

Conclusion

Cypress is a fantastic testing framework for ReactJS applications, offering a developer-friendly experience and powerful testing capabilities. In this blog post, we’ve covered the basics of setting it up in a ReactJS project and writing tests for various scenarios. 

Happy testing!

Note:- Cypress testing can be done via CLI as well, which is not included in this blog.

References:

  1. Cypress docs

Related content

That’s all for this blog

Go to Top