Skip to content

Commit

Permalink
Merge pull request #298 from Mcat12/fix/throw-in-catch
Browse files Browse the repository at this point in the history
Fix asserting a throw in a catch block
  • Loading branch information
jp928 committed Sep 4, 2019
2 parents 7f68a83 + fca2c5c commit 1b52329
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
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

0 comments on commit 1b52329

Please sign in to comment.