Last active
May 28, 2022 08:37
-
-
Save mangosmoothie/8983b99f3d7ddcf7ee12e1a8d6841aad to your computer and use it in GitHub Desktop.
redux-mock-store with redux-saga for testing actions / sagas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/arnaudbenard/redux-mock-store/issues/59#issuecomment-345741265 | |
//------------- the saga ---------------- | |
function* fetchSaga(action) { | |
try { | |
yield put({type: "FETCH_SUCCEEDED", data: "data"}); | |
} catch (e) { | |
yield put({type: "FETCH_FAILED", message: e.message}); | |
} | |
} | |
function* watchers() { | |
yield takeEvery("FETCH", fetchSaga); | |
} | |
// -------------- the test ----------------- | |
const sagaMiddleware = createSagaMiddleware(); | |
const mockStore = configureStore([sagaMiddleware]); | |
describe('the sagas', () => { | |
it('should execute YOUR_SAGA', (done) => { | |
const store = mockStore({}); | |
sagaMiddleware.run(watchers); // has to be executed after the mockStore() call | |
const expectedActions = [ | |
{ "type": "FETCH" }, | |
{ "type": "FETCH_SUCCEEDED", data: "data"} | |
]; | |
store.subscribe(() => { | |
const actions = store.getActions(); | |
if (actions.length >= expectedActions.length){ | |
expect(actions).toEqual(expectedActions); | |
done(); | |
} | |
}); | |
// Return the promise | |
store.dispatch({ type: "FETCH" }); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment