Testing a saga means manually stepping through the generator function and asserting that it yields the expected effects in order.
1. Sample Saga to Test
import { call, put } from 'redux-saga/effects';
import { fetchDataApi } from './api';
function* fetchDataSaga(action) {
try {
const data = yield call(fetchDataApi, action.payload);
yield put({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
yield put({ type: 'FETCH_FAILURE', error: error.message });
}
}
2. Test Using Jest
import { call, put } from 'redux-saga/effects';
import { fetchDataSaga } from './sagas';
import { fetchDataApi } from './api';
describe('fetchDataSaga', () => {
const action = { type: 'FETCH_REQUEST', payload: 1 };
const generator = fetchDataSaga(action);
it('should call fetchDataApi with correct payload', () => {
expect(generator.next().value).toEqual(call(fetchDataApi, 1));
});
it('should dispatch FETCH_SUCCESS on success', () => {
const mockResponse = { name: 'Test' };
expect(generator.next(mockResponse).value).toEqual(
put({ type: 'FETCH_SUCCESS', payload: mockResponse })
);
});
it('should handle errors with FETCH_FAILURE', () => {
const errorGen = fetchDataSaga(action);
errorGen.next(); // skip to call
const error = new Error('API failed');
expect(errorGen.throw(error).value).toEqual(
put({ type: 'FETCH_FAILURE', error: 'API failed' })
);
});
});