Skip to content

Instantly share code, notes, and snippets.

@gaelollivier
Created October 24, 2016 21:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaelollivier/46ffe7d9b90d8b527db2a631c4ae7393 to your computer and use it in GitHub Desktop.
Save gaelollivier/46ffe7d9b90d8b527db2a631c4ae7393 to your computer and use it in GitHub Desktop.
Examples of Snapshot testing a Redux Saga
/**
* Basic saga that revokes session and redirects to /login
* each time a LOGOUT action is dispatched
*/
function* logoutSaga() {
while (true) {
yield take(LOGOUT)
yield put(revokeSession())
yield put(redirect('/login'))
}
}
/**
* Testing this with snapshot testing
*/
it('should revoke session and redirect to login', () => {
const gen = logoutSaga()
// Iterate 4 times, to ensure `done` is still false after the first loop
for (let i=0; i < 4; ++i) {
expect(gen.next()).toMatchSnapshot()
}
})
/**
* Bit more complex saga, that expects a returned value
*/
function* fetchUserSaga() {
while (true) {
yield take(FETCH_USER)
try {
const user = yield call(Api.fetchUser)
yield put({ type: FETCH_USER_SUCCESS, payload: user })
} catch (e) {
yield put({ type: FETCH_USER_FAIL, error: true, payload: e })
}
}
}
it('should dispatch a FETCH_USER_SUCCESS', () => {
const gen = fetchUserSaga()
// Take FETCH_USER
expect(gen.next()).toMatchSnapshot()
// Call API
expect(gen.next({ id: 42, name: 'John Doe' })).toMatchSnapshot()
// Dispatch FETCH_USER_SUCCESS
expect(gen.next()).toMatchSnapshot()
// Loop
expect(gen.next()).toMatchSnapshot()
})
it('should dispatch a FETCH_USER_FAIL', () => {
const gen = fetchUserSaga()
// Take FETCH_USER
expect(gen.next()).toMatchSnapshot()
// Call API
expect(gen.throw({ code: 404 })).toMatchSnapshot()
// Dispatch FETCH_USER_FAIL
expect(gen.next()).toMatchSnapshot()
// Loop
expect(gen.next()).toMatchSnapshot()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment