Skip to content

Commit ed5daf7

Browse files
committed
Handle promise exceptions
1 parent 844f10a commit ed5daf7

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

src/__snapshots__/index.test.js.snap

+10
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ exports[`jest-expect-message should fail with custom message 1`] = `
99
Received: <red>false</color>"
1010
`;
1111

12+
exports[`jest-expect-message should fail with custom message for async test 1`] = `
13+
"Custom message:
14+
hello
15+
16+
<dim>expect(</intensity><red>received</color><dim>).</intensity>rejects<dim>.</intensity>toBe<dim>(</intensity><green>expected</color><dim>) // Object.is equality</intensity>
17+
18+
Expected: <green>false</color>
19+
Received: <red>true</color>"
20+
`;
21+
1222
exports[`jest-expect-message should fail without custom message 1`] = `
1323
"<dim>expect(</intensity><red>received</color><dim>).</intensity>toBeTruthy<dim>()</intensity>
1424

src/index.test.js

+6
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ describe('jest-expect-message', () => {
55
expect(() => expect(false, 'Woah this should be false!').toBeTruthy()).toThrowErrorMatchingSnapshot();
66
});
77

8+
test('should fail with custom message for async test', async () => {
9+
await expect(
10+
async () => await expect(Promise.reject(true), 'hello').rejects.toBe(false)
11+
).rejects.toThrowErrorMatchingSnapshot();
12+
});
13+
814
test('should fail without custom message', () => {
915
expect(() => expect(false).toBeTruthy()).toThrowErrorMatchingSnapshot();
1016
});

src/withMessage.js

+14-2
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,20 @@ class JestAssertionError extends Error {
1212
const wrapMatcher = (matcher, customMessage, config) => {
1313
const newMatcher = (...args) => {
1414
try {
15-
return matcher(...args);
16-
} catch (error) {
15+
const result = matcher(...args);
16+
17+
if (result && typeof result.then === 'function') {
18+
return result.catch(rethrowWithMessage).catch(function handleError(error) {
19+
throw new JestAssertionError(error.matcherResult, handleError);
20+
});
21+
} else {
22+
return result;
23+
}
24+
} catch (e) {
25+
rethrowWithMessage(e);
26+
}
27+
28+
function rethrowWithMessage(error) {
1729
if (!error.matcherResult) {
1830
throw error;
1931
}

0 commit comments

Comments
 (0)