Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix asserting a throw in a catch block #298

Merged
merged 1 commit into from
Sep 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 48 additions & 1 deletion __tests__/expectSaga/assertions/throws.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/* eslint-disable require-yield */
import { put } from 'redux-saga/effects';
import { call, put } from 'redux-saga/effects';
import expectSaga from 'expectSaga';
import { throwError } from 'expectSaga/providers';

class CustomError {}

function myFunction() {}

function* noErrorSaga() {
yield put({ type: 'TEST_1' });
yield put({ type: 'TEST_2' });
Expand All @@ -13,6 +16,14 @@ function* errorSaga(errorToThrow) {
throw errorToThrow;
}

function* throwInCatch() {
try {
yield call(myFunction);
} catch (e) {
throw e;
}
}

test('matches based on error type', () =>
expectSaga(errorSaga, new CustomError('Error Message'))
.throws(CustomError)
Expand Down Expand Up @@ -94,3 +105,39 @@ test('exception bubbles up when no error expected', done => {
done();
});
});

test('matches exception when thrown in catch', () => {
const error = { message: 'test error' };

return expectSaga(throwInCatch)
.provide([[call(myFunction), throwError(error)]])
.throws(error)
.run();
});

test('fails when non-matching exception is thrown in catch', done => {
const error = { message: 'test error' };
const differentError = { message: 'test error 2' };

return expectSaga(throwInCatch)
.provide([[call(myFunction), throwError(differentError)]])
.throws(error)
.run()
.catch(e => {
expect(e.message).toMatch(/but instead threw/i);
done();
});
});

test('negative assertion fails when matching exception is thrown in catch', done => {
const error = { message: 'test error' };

return expectSaga(throwInCatch)
.provide([[call(myFunction), throwError(error)]])
.not.throws(error)
.run()
.catch(e => {
expect(e.message).toMatch(/expected not to throw/i);
done();
});
});
9 changes: 8 additions & 1 deletion src/expectSaga/sagaWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,14 @@ export default function createSagaWrapper(
},

throw(e, fsm) {
result = wrappedIterator.throw(e);
try {
result = wrappedIterator.throw(e);
} catch (innerError) {
if (typeof onError === 'function') {
onError(innerError);
}
throw innerError;
}
return fsm[LOOP](undefined, fsm);
},
});
Expand Down