everyone. I test saga with jest framework. I can test my saga in normal situation. But I want to test the code in catch(), so I have to mock a error to trigger catch. I find some solution in redux-saga offical document and other stackoverflow answer. But I still have a problem.
when I use throw() in saga.test.js like the sample below, it will show "Error [object Object] thrown". So it can't really pass this test. I didn't see anyone ask same question. Could anyone help me? Thanks a lot.
Error result screen:
api.js
const api = {
fetchProductAPI() {
return 'iphone';
},
};
export default api;
saga.js
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 });
}
}
saga.test.js
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();
expect(
gen.throw({
error: 'product not found',
}).value
).toEqual(put({ type: 'PRODUCTS_REQUEST_FAILED', error }));
});
});
The related solutions answer I found below: