diff --git a/packages/expect/src/__tests__/stacktrace.test.js b/packages/expect/src/__tests__/stacktrace.test.js new file mode 100644 index 000000000000..3cbdd6b77a12 --- /dev/null +++ b/packages/expect/src/__tests__/stacktrace.test.js @@ -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'); + } +}); diff --git a/packages/expect/src/index.js b/packages/expect/src/index.js index e7927452a64c..e592d16bdc62 100644 --- a/packages/expect/src/index.js +++ b/packages/expect/src/index.js @@ -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; }