Skip to content

Commit

Permalink
Handle promise exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
mattphillips committed Sep 8, 2022
1 parent 844f10a commit ed5daf7
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ exports[`jest-expect-message should fail with custom message 1`] = `
Received: <red>false</color>"
`;

exports[`jest-expect-message should fail with custom message for async test 1`] = `
"Custom message:
hello
<dim>expect(</intensity><red>received</color><dim>).</intensity>rejects<dim>.</intensity>toBe<dim>(</intensity><green>expected</color><dim>) // Object.is equality</intensity>
Expected: <green>false</color>
Received: <red>true</color>"
`;

exports[`jest-expect-message should fail without custom message 1`] = `
"<dim>expect(</intensity><red>received</color><dim>).</intensity>toBeTruthy<dim>()</intensity>
Expand Down
6 changes: 6 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ describe('jest-expect-message', () => {
expect(() => expect(false, 'Woah this should be false!').toBeTruthy()).toThrowErrorMatchingSnapshot();
});

test('should fail with custom message for async test', async () => {
await expect(
async () => await expect(Promise.reject(true), 'hello').rejects.toBe(false)
).rejects.toThrowErrorMatchingSnapshot();
});

test('should fail without custom message', () => {
expect(() => expect(false).toBeTruthy()).toThrowErrorMatchingSnapshot();
});
Expand Down
16 changes: 14 additions & 2 deletions src/withMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,20 @@ class JestAssertionError extends Error {
const wrapMatcher = (matcher, customMessage, config) => {
const newMatcher = (...args) => {
try {
return matcher(...args);
} catch (error) {
const result = matcher(...args);

if (result && typeof result.then === 'function') {
return result.catch(rethrowWithMessage).catch(function handleError(error) {
throw new JestAssertionError(error.matcherResult, handleError);
});
} else {
return result;
}
} catch (e) {
rethrowWithMessage(e);
}

function rethrowWithMessage(error) {
if (!error.matcherResult) {
throw error;
}
Expand Down

0 comments on commit ed5daf7

Please sign in to comment.