Unit Testing React Form with Jest and Enzyme
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Enzyme, Form, Jest, React, Unit Test
Jest is a JavaScript unit testing framework created by Facebook. I usually use mocha for unit testing Node.js code, but when it comes to testing React, Jest combined with Enzyme is pretty much the best. Enzyme is a JavaScript utility library created by Airbnb. It lets you simulate DOM rendering and actions on the components and integrates well with Jest.
In this post, I am focusing on testing React form. When I first started writing unit tests on React form components, I spent a bit of time investigating and experimenting different ways. I especially struggled to write a unit test on multi-select and checkbox component. So, here it is.
Focus
- Testing a simple text input
- Testing checkbox
- Testing Multi-select options.
- Testing alert() function on form submit.
Complete Solution
This blog focuses purely on unit test code. You can check out the complete solutions here: react-form-unit-test-example.
Unit Test Code
Here is the main Form component to be tested.
(1) Testing Text Input
Testing text input is relatively simple. First mount the component with Enzyme’s mount function, then set the value and simulate the change. When there are multiple input fields, we can use .at(0) to find the input element by index.
(2) Testing Checkbox
For checkbox, assign the value for checked instead of value and then simulate change.
(3) Testing Multi-Select
To test multi-select, you need to set the individual option’s selected property to true. This solution works.
Simulating change on the select element as below doesn’t work.
(4) Testing alert() on Submit
On submit, it will call the alert function with all the input values (see here). To test this logic, we need to mock window.alert function and check if it is called with the correct argument, including all the input values. First, set the state and simulate submit. Then, check to see if mocked alert function is called with the value from the state.