Blog>
Snippets

Using cloneableGenerator for Branching Logic

Use `cloneableGenerator` to test a saga with branching logic, showing how to clone the generator's state before testing each branch.
import { cloneableGenerator } from 'redux-saga/utils';
import { take, put } from 'redux-saga/effects';
import { mySaga, actionCreators } from './sagas';
Import necessary functions and the saga you are testing.
const gen = cloneableGenerator(mySaga)();
Create a cloneable generator instance of the saga.
// Assuming the first yield in the saga waits for an action
gen.next();
Advances the generator to the first yield.
const clone = gen.clone();
Clone the generator's state before branching logic.
// Test the first branch
gen.next(actionCreators.successAction());
expect(gen.next().value).toEqual(put({type: 'SUCCESS'}));
Test the first branch of the saga.
// Test the second branch using the cloned generator
clone.next(actionCreators.failureAction());
expect(clone.next().value).toEqual(put({type: 'FAILURE'}));
Use the cloned generator to test the second branch without restarting.