If you are bootstrapping your react apps with create-react-app you may be aware that Jest is now baked in. Jest is yet another FB creation that aims to simplify writing javascript unit tests. It’s currently gaining traction and you can find really good Jest tutorials here, here and here.
This introductory tutorial focuses on writing tests for Redux enabled React apps, more specifically writing tests for your Actions and Reducers.
Getting started:
yarn add jest
yarn test watch options
Yarn has a built in regex that will search ALL LEVELS of your src folder, out of the box it searches for files that fit one of the following 3 criteria:
*Files with `.js` suffix in `__tests__` folders.
*Files with `.test.js` suffix.
*Files with `.spec.js` suffix.
OK, so lets write a simple first test. We are going to begin with testing a very simple Action creator. If you are not familiar with the difference between Actions and Action creators, read this.
Here is an actionsJS file with a single const SET_SELECTED_ACCT and and Action Creator: setSelectedAccount(). This is the Action creator that we will be testing.
actions.js
This is our test file. We import everything from our actions.js file, set a fake accountNumber to test with and then begin our test. Line 5 and 6 describe our test(you could put multiple it tests inside of a describe), line 8 begins our mocked expected response and line 12 executes our action and uses a toEqual matcher to make the comparison of received vs expected.
Your terminal will output something like the following upon success, if errors there will be context for the failure in the terminal.
watch options results
Now let’s test a reducer. Reducers can be complex but writing tests for them is fairly simple as they are just JS functions.
reducers.js
This is a simple reducer file with a single reducer: selectedAccount. Notice we reference the same const SET_SELECTED_ACCOUNT from out actions.js file.
This describe function contains 2 tests, line 6 and line 9. Line 6 tests for an initial state of selectedAccount: null. Line 9 executes the reducer with an undefined state(line 12) and an Action with 2 properties: selectedAccount and type. This is the same Action we tested earlier. Line 18 ensures that the reducer returns the accountNumber.
That is pretty much it for this intro to testing Redux Actions and Reducers using Jest. We added Jest to our project, created tests for an Action creator and a Reducer in our test.js file and took a look at some of the terminal inputs and outputs for navigating Jest tests.
Let me know your thoughts on twitter. Keep after it.