Unit Testing a Saga with Redux-Saga Test Plan
Provide an example of how to unit test a saga using Redux-Saga Test Plan, demonstrating how to mock effects and assert that the saga dispatches the expected actions under certain conditions.
import { expectSaga } from 'redux-saga-test-plan';
import { call, put } from 'redux-saga/effects';
import { fetchUserData, userDataReceived } from './actions';
import { getUserData } from './api';
import { fetchUserDataSaga } from './sagas';
First, we import necessary functions and variables. 'expectSaga' is used to create an assertion around our saga. 'call' and 'put' are effect creators from Redux-Saga. The actions 'fetchUserData' and 'userDataReceived', the API function 'getUserData', and our saga 'fetchUserDataSaga' are also imported.
const mockUser = { id: 1, name: 'John Doe' };
Define a mock data for the user, that we will use as a response from our simulated API call.
it('fetches user data and dispatches success action', () => {
return expectSaga(fetchUserDataSaga, fetchUserData())
.provide([[call(getUserData), mockUser]])
.put(userDataReceived(mockUser))
.run();
});
We define our test case. Using 'expectSaga', we pass our saga along with any initial action it requires. With '.provide', we mock the response of our 'getUserData' call to return 'mockUser'. We then assert that our saga will eventually 'put' (dispatch) a 'userDataReceived' action with the mock user data. '.run()' executes the test.