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…
- remove all the generated files in cypress/integration tests folder
-
add below to cypress/support/index.js
require('@cypress/react/support')
-
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 }
-
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
Ok lets create the test file:
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
Nice!
Oh and a bonus code coverage report…
100% code coverage. 👌
As you can see the cypress component testing library is really awesome.
Thanks to Cypress react testing lib