Handling Saga Branching Logic in Tests
Example of testing a saga that contains branching logic (if/else paths), showing how to test both branches and ensure all paths are covered by tests.
import { runSaga } from 'redux-saga';
import { select, put } from 'redux-saga/effects';
import { mySaga } from './sagas';
import { initialState } from './reducer';
// Mock data
const mockData = { value: 10 };
Sets up the test environment by importing necessary functions and the saga to be tested. Also, initializes mock data and state.
test('handles if branch of saga', async () => {
const dispatched = [];
await runSaga({
dispatch: (action) => dispatched.push(action),
getState: () => ({ ...initialState, data: mockData })
}, mySaga).toPromise();
// Assertions for the if branch
expect(dispatched).toContainEqual(expectedActionForIfBranch);
});
Tests the 'if' branch of the saga by providing a state that meets the condition, then asserts that the expected action for the 'if' branch is dispatched.
test('handles else branch of saga', async () => {
const dispatched = [];
await runSaga({
dispatch: (action) => dispatched.push(action),
getState: () => ({ ...initialState }) // State that triggers else branch
}, mySaga).toPromise();
// Assertions for the else branch
expect(dispatched).toContainEqual(expectedActionForElseBranch);
});
Tests the 'else' branch of the saga by providing an initial state that does not meet the 'if' condition, then asserts that the expected action for the 'else' branch is dispatched.