Martin McGee's Blog

How to unit test React components with Cypress

January 23, 2021

cypress and react

Unit testing React Components

Testing tools such as Jest, Enzyme and the React Testing Library are currently the most popular unit testing tools for testing React components.

While they are very fast, they only simulate a browser using jsdom and not a real one like a user would.

Cypress Unit testing

Cypress can be used to unit test React components and offers unit testing in a REAL browser whilst also having access to all of the awesome features of Cypress, like having a live GUI to ‘see’ your unit tests in action!

Cool!

Getting started with Cypress Unit testing

Assuming we are starting with a blank project lets start with create react app

run:

npx create-react-app unit-test-react-component-cypress
cd unit-test-react-component-cypress

After the internet downloads lets install cypress and @cypress/react

npm install --save-dev cypress @cypress/react

Now start cypress which adds all of the config files

npx cypress open

Ok some configuration to do…

  1. remove all the generated files in cypress/integration tests folder
  2. add below to cypress/support/index.js

    require('@cypress/react/support')
  3. add below line to cypress/plugins/index.js

    // cypress/plugins/index.js
    module.exports = (on, config) => {
    require('@cypress/react/plugins/react-scripts')(on, config)
    // IMPORTANT to return the config object
    // with the any changed environment variables
    return config
    }
  4. then finally turn the experimental option on..

    {
    "experimentalComponentTesting": true,
    "componentFolder": "src"
    }

    SETUP DONE 👌

Next we need to create a react component to test..

Create a React component

Ok lets create a component to test, im using a counter component with react hooks found here by Esther

src/Counter.js Counter React Component

Ok lets create the test file:

Counter React Component Tests

As you can see it looks similar to a usual cypress UI test, but we can use REAL clicks and not simulation like a real user would.

Lets run it:

npx cypress open

Counter React Component Tests

Nice!

Oh and a bonus code coverage report…

Code coverage 100%

100% code coverage. 👌

As you can see the cypress component testing library is really awesome.

Source code to the blog

Thanks to Cypress react testing lib