Blog>
Snippets

Testing Generator Function Step Sequence

Demonstrate testing the step sequence of a Redux-Saga generator function, ensuring `call`, `put`, and `take` effects yield in the correct order.
import { call, put, takeEvery } from 'redux-saga/effects';
function* mySaga() {
  // Here would usually go some API call
  const data = yield call(fetchData, 'http://example.com/data');
  // Dispatch an action with the result
  yield put({type: 'DATA_LOADED', payload: data});
}
This piece of code defines a Redux-Saga generator function named `mySaga`. It demonstrates the use of `call` to invoke an API call, then uses `put` to dispatch an action with the fetched data.
import { call } from 'redux-saga/effects';
import { fetchData } from '../api';
describe('mySaga', () => {
  const gen = mySaga();
  it('should call fetchData with the correct URL', () => {
    expect(gen.next().value).toEqual(call(fetchData, 'http://example.com/data'));
  });
  it('should dispatch DATA_LOADED action', () => {
    gen.next(); // to skip fetching result
    expect(gen.next().value).toEqual(put({type: 'DATA_LOADED', payload: undefined}));
  });
});
This code snippet demonstrates how to test the sequence of operations in `mySaga`. It uses `expect` to assert that the `call` and `put` effects yield in the correct order, using `gen.next().value` to step through the generator.