Skip to content

Commit

Permalink
Add error call site to preserve stack trace;
Browse files Browse the repository at this point in the history
  • Loading branch information
mattphillips committed Jan 29, 2020
1 parent 5322fc7 commit 30b7573
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/chain.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
class JestAssertionError extends Error {
constructor(result, callsite) {
super(result.message());
this.matcherResult = result;

if (Error.captureStackTrace) {
Error.captureStackTrace(this, callsite);
}
}
}

const chainMatchers = (matchers, originalMatchers = matchers) => {
const mappedMatchers = Object.keys(matchers).map(name => {
const matcher = matchers[name];
if (typeof matcher === 'function') {
return {
[name]: (...args) => {
const newMatcher = (...args) => {
try {
matcher(...args); // run matcher
return chainMatchers(originalMatchers); // chain the original matchers again
} catch (error) {
throw new JestAssertionError(error.matcherResult, newMatcher);
}
};
return { [name]: newMatcher };
}
return {
[name]: chainMatchers(matcher, originalMatchers) // recurse on .not/.resolves/.rejects
Expand Down
13 changes: 13 additions & 0 deletions src/chain.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,17 @@ describe('.chain', () => {
expect(extendMock).toHaveBeenCalledWith(newMatcher);
expect(actual).toContainAllKeys(['a', 'extend', 'newMatcher']);
});

it('throws error when matcher fails', () => {
expect.assertions(1);
const expectMock = jest.fn(() => ({
toBe: () => {
const error = new Error('');
error.matcherResult = { message: () => 'blah', pass: false };
throw error;
}
}));

expect(() => chain(expectMock)('hello').toBe('hi')).toThrowErrorMatchingInlineSnapshot('"blah"');
});
});

0 comments on commit 30b7573

Please sign in to comment.