Testing Your React Component With Jest and Enzyme
In addition, “Jest parallelizes test runs across workers to maximize performance. Console messages are buffered and printed together with test results. Sandboxed test files and automatic global state resets for every test so no two tests conflict with each other.”
Therefore, in this tutorial, we’ll walk through a step-by-step guide on how to test your react components using the Jest testing framework and Enzyme.
The first thing you want to do is install Jest and Enzyme. Type the following command in your terminal:
npm install jest enzyme --save-dev
After installation, create a __tests__ folder in your app. This would contain all tests to be written for the app. “Why ‘__tests__’?” you’d say. Well, that’s the recommended folder naming convention adopted in Jest.
Testing React Components
Testing react components is quite easy with Snapshot Testing (this a useful test tool that ensures UI components do not change unexpectedly). Basically, Snapshot Testing involves analysing how app components change over time.
Luckily, Jest makes Snapshot Testing effortless. In Jest, a snapshot test case for a react component renders the component, takes a screenshot of the rendered component, and compares it with a referenced image stored during the test. The test fails if the screenshot and referenced image do not match. In such an instance, the change was either unexpected or the component was updated (in which case, the snapshot also needs to be updated).
For this tutorial, I’ve created a simple ToDO app which displays an input field, a button, and a table. You can view the app on GitHub.
The button component (labelled ‘ADD ITEM’) is defined below:
A simple snapshot test for this component can be defined as below:
Sometimes, a snapshot error such as the image below might occur:
To fix this error, run jest — updateSnapshot. This updates the snapshot and reference image.
Testing the Button Component Further
Testing a Button Click Event
To test a click event, Jest provides a manual mocking functionality that allows us to create mock functions. A mock function can be as simple as
const mockFn = jest.fn();
Also a click event can be simulated with Enzyme using the simulate() function.
Some Handy Jest Methods
Important Testing Tips
- Ensure your test suites and cases clearly communicate what is being tested.
- Ensure your test file contains test cases for a single component or function
- Ensure that the test file name matches the component being tested.