Skip to content

Commit

Permalink
Do not modify stack trace of JestAssertionError (#4516)
Browse files Browse the repository at this point in the history
* Do not modify stack trace of JestAssertionError.

* Added test for stack trace of nested matchers.

* Fixed test for nested matcher and added test for normal matchers.

* Only comparing line numbers in test because function names in stack trace seem to be platform dependent.
  • Loading branch information
denniske authored and cpojer committed Sep 20, 2017
1 parent 246da7f commit fbacd19
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
38 changes: 38 additions & 0 deletions packages/expect/src/__tests__/stacktrace.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/

const jestExpect = require('../');

jestExpect.extend({
toMatchPredicate(received, argument) {
argument(received);
return {
message: () => '',
pass: true,
};
},
});

it('stack trace points to correct location when using matchers', () => {
try {
jestExpect(true).toBe(false);
} catch (error) {
expect(error.stack).toContain('stacktrace.test.js:24');
}
});

it('stack trace points to correct location when using nested matchers', () => {
try {
jestExpect(true).toMatchPredicate(value => {
jestExpect(value).toBe(false);
});
} catch (error) {
expect(error.stack).toContain('stacktrace.test.js:33');
}
});
10 changes: 6 additions & 4 deletions packages/expect/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,12 @@ const makeThrowingMatcher = (
try {
result = matcher.apply(matcherContext, [actual].concat(args));
} catch (error) {
// Try to remove this and deeper functions from the stack trace frame.
// Guard for some environments (browsers) that do not support this feature.
if (Error.captureStackTrace) {
Error.captureStackTrace(error, throwingMatcher);
if (!(error instanceof JestAssertionError)) {
// Try to remove this and deeper functions from the stack trace frame.
// Guard for some environments (browsers) that do not support this feature.
if (Error.captureStackTrace) {
Error.captureStackTrace(error, throwingMatcher);
}
}
throw error;
}
Expand Down

0 comments on commit fbacd19

Please sign in to comment.