Skip to content

Instantly share code, notes, and snippets.

@Hsueh-Jen
Last active March 23, 2018 09:23
Show Gist options
  • Save Hsueh-Jen/e70c59ab5638912b17c8c4e9cfc9b7f5 to your computer and use it in GitHub Desktop.
Save Hsueh-Jen/e70c59ab5638912b17c8c4e9cfc9b7f5 to your computer and use it in GitHub Desktop.
test saga try and catch
const api = {
fetchProductAPI() {
return 'iphone';
},
};
export default api;
import { call, put } from 'redux-saga/effects';
import api from './api';
export default function* fetchProduct() {
try {
yield call(api.fetchProductAPI);
yield put({ type: 'PRODUCTS_RECEIVED', product: 'iphone' });
} catch (error) {
yield put({ type: 'PRODUCTS_REQUEST_FAILED', error });
}
}
/* eslint-disable redux-saga/yield-effects */
import { put, call } from 'redux-saga/effects';
import fetchProduct from './saga';
import api from './api';
describe('fetchProduct()', () => {
it('try', () => {
const gen = fetchProduct();
expect(gen.next().value).toEqual(call(api.fetchProductAPI));
expect(gen.next().value).toEqual(put({ type: 'PRODUCTS_RECEIVED', product: 'iphone' }));
});
it('catch', () => {
const error = 'product not found';
const gen = fetchProduct();
gen.next(); // <== before throw error, you need to execute gen.next();
expect(gen.throw('product not found').value).toEqual(put({ type: 'PRODUCTS_REQUEST_FAILED', error }));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment