Redux-Saga UnitTesting
State Management is the most important thing in React or React-Native. State management is essentially a way to facilitate communication and sharing of data across components in apps, mostly we use Redux-Saga.
Today, I want to share about “ How we can write Unit Test in Redux-Saga ?”
There are too many ways to write unit testing in redux-saga, the easiest way is to use 3rd party lib like redux-saga-testing, etc. But today, we will only use jest to test each function in redux-saga (reducer, action, and saga), and tap-spec to test the flow state in redux-saga.
Usually, redux-saga has action, reducer, and saga components. First, let’s begin with Jest to test each function
Action
To test this in function test, we only test the parameters and the return like this example :
Reducer
To test this in function test, we also only test the parameters and the return like this example :
Saga
This is the important and the tricky part to test each function in the saga. First, we must import the “runSaga” from the redux-saga lib
The second one, we create a mock Store and dispatch to mock the “state”
So the idea is every time we dispatch the state, changes will be push into the dispatchedActions empty array
After that, we write our unit test to test the saga function :
We have already tried to test each function for an action, reducer, and saga in redux-saga. How can we test the flow state management on this? Well, we can use “tape”. Please check this example flow state management test :
And that’s it…so in this time, we test each function and test the flow state management in redux-saga
last but not least…I uploaded my playground for the redux-saga unit testing, feel free to use it, add it, or modify it: REDUX-SAGA-UNIT-TEST-PLAYGROUND
Happy Coding Guys….!