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.
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.
Now let’s test a reducer. Reducers can be complex but writing tests for them is fairly simple as they are just JS functions.
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.
Create your free account to unlock your custom reading experience.