Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Discussion] Expect only overrides error stack for built-in matchers #5162

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
f39d750
Expect only overrides error stack for built-in matchers
bvaughn Dec 22, 2017
e7d9bbd
Fixed naggy lint issue
bvaughn Dec 22, 2017
9c10921
Replaced for...of with Object.keys().forEach()
bvaughn Dec 22, 2017
eb5d29c
Merged master
bvaughn Jan 2, 2018
ea088cf
Removed JestAssertionError export (as it is no longer needed)
bvaughn Jan 2, 2018
f2e7335
Added custom matcher test
bvaughn Jan 2, 2018
3e00753
Adjusted custom_matcher test to use prettified, non-absolute stack
bvaughn Jan 3, 2018
9e0cfae
test: refactor integration test
SimenB Jan 3, 2018
31f8e58
update with correct snapshot
SimenB Jan 3, 2018
c388a49
test: skip on windows
SimenB Jan 3, 2018
0c5c78c
Clarified comment
bvaughn Jan 3, 2018
5843ab5
Further clarified comment
bvaughn Jan 3, 2018
f902b4b
test: fix test for node 6
SimenB Jan 3, 2018
bd21922
test: move custom matcher stack to separate file to be able to skip i…
SimenB Jan 3, 2018
3ef09ea
Revert "test: fix test for node 6"
SimenB Jan 3, 2018
f88bf07
test: really fix node 6
SimenB Jan 3, 2018
ff50df6
Merge branch 'master' into override-error-stack-only-for-internal-mat…
SimenB Jan 4, 2018
2da0eee
docs: add package prefix to changelog
SimenB Jan 4, 2018
6f6dd91
Merge branch 'master' into override-error-stack-only-for-internal-mat…
bvaughn Jan 4, 2018
e8ab539
Reverted unrelated Markdown changes that had made their way into the …
bvaughn Jan 4, 2018
7dad466
Replaced '__jestInternal' string attribute with a Symbol
bvaughn Jan 4, 2018
179093c
Merge branch 'master' into override-error-stack-only-for-internal-mat…
bvaughn Jan 5, 2018
b8c6bfe
Updated snapshot
bvaughn Jan 5, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
Windows platform. ([#5161](https://github.com/facebook/jest/pull/5161))
* `[jest-regex-util]` Fix breaking change in `--testPathPattern`
([#5230](https://github.com/facebook/jest/pull/5230))
* `[expect]` Do not override `Error` stack (with `Error.captureStackTrace`) for
custom matchers. ([#5162](https://github.com/facebook/jest/pull/5162))

### Features

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`works with custom matchers 1`] = `
"FAIL __tests__/custom_matcher.test.js
Custom matcher
✓ passes
✓ fails
✕ preserves error stack

● Custom matcher › preserves error stack

qux

43 | const bar = () => baz();
44 | const baz = () => {
> 45 | throw Error('qux');
46 | };
47 |
48 | // This expecation fails due to an error we throw (intentionally)

at __tests__/custom_matcher.test.js:45:13
at __tests__/custom_matcher.test.js:43:23
at __tests__/custom_matcher.test.js:42:23
at __tests__/custom_matcher.test.js:52:7
at __tests__/custom_matcher.test.js:11:18
at __tests__/custom_matcher.test.js:53:8

"
`;
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ exports[`works with async failures 1`] = `
+ \\"foo\\": \\"bar\\",
}

at ../../packages/expect/build/index.js:155:54
at ../../packages/expect/build/index.js:156:54

"
`;
Expand Down
28 changes: 28 additions & 0 deletions integration_tests/__tests__/custom_matcher_stack_trace.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';

const runJest = require('../runJest');
const {extractSummary} = require('../utils');
const skipOnWindows = require('../../scripts/skip_on_windows');

skipOnWindows.suite();

test('works with custom matchers', () => {
const {stderr} = runJest('custom_matcher_stack_trace');

let {rest} = extractSummary(stderr);

rest = rest
.split('\n')
.filter(line => line.indexOf('at Error (native)') < 0)
.join('\n');

expect(rest).toMatchSnapshot();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';

function toCustomMatch(callback, expectation) {
const actual = callback();

if (actual !== expectation) {
return {
message: () => `Expected "${expectation}" but got "${actual}"`,
pass: false,
};
} else {
return {pass: true};
}
}

expect.extend({
toCustomMatch,
});

describe('Custom matcher', () => {
it('passes', () => {
// This expectation should pass
expect(() => 'foo').toCustomMatch('foo');
});

it('fails', () => {
expect(() => {
// This expectation should fail,
// Which is why it's wrapped in a .toThrow() block.
expect(() => 'foo').toCustomMatch('bar');
}).toThrow();
});

it('preserves error stack', () => {
const foo = () => bar();
const bar = () => baz();
const baz = () => {
throw Error('qux');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be throw new Error? I'm not sure if there's a semantical difference...

Copy link
Contributor Author

@bvaughn bvaughn Jan 5, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No difference that I'm aware of.

15.11.1 The Error Constructor Called as a Function

When Error is called as a function rather than as a constructor, it creates and initialises a new Error object. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.

source: http://ecma-international.org/ecma-262/5.1/#sec-15.11.1

};

// This expecation fails due to an error we throw (intentionally)
// The stack trace should point to the line that throws the error though,
// Not to the line that calls the matcher.
expect(() => {
foo();
}).toCustomMatch('test');
});
});
5 changes: 5 additions & 0 deletions integration_tests/custom_matcher_stack_trace/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
32 changes: 30 additions & 2 deletions packages/expect/src/__tests__/stacktrace.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
const jestExpect = require('../');

jestExpect.extend({
toCustomMatch(callback, expectation) {
const actual = callback();

if (actual !== expectation) {
return {
message: () => `Expected "${expectation}" but got "${actual}"`,
pass: false,
};
}

return {pass: true};
},
toMatchPredicate(received, argument) {
argument(received);
return {
Expand All @@ -22,7 +34,7 @@ it('stack trace points to correct location when using matchers', () => {
try {
jestExpect(true).toBe(false);
} catch (error) {
expect(error.stack).toContain('stacktrace.test.js:23');
expect(error.stack).toContain('stacktrace.test.js:35');
}
});

Expand All @@ -32,6 +44,22 @@ it('stack trace points to correct location when using nested matchers', () => {
jestExpect(value).toBe(false);
});
} catch (error) {
expect(error.stack).toContain('stacktrace.test.js:32');
expect(error.stack).toContain('stacktrace.test.js:44');
}
});

it('stack trace points to correct location when throwing from a custom matcher', () => {
try {
jestExpect(() => {
const foo = () => bar();
const bar = () => baz();
const baz = () => {
throw new Error('Expected');
};

foo();
}).toCustomMatch('bar');
} catch (error) {
expect(error.stack).toContain('stacktrace.test.js:57');
}
});
11 changes: 7 additions & 4 deletions packages/expect/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
stringMatching,
} from './asymmetric_matchers';
import {
INTERNAL_MATCHER_FLAG,
getState,
setState,
getMatchers,
Expand Down Expand Up @@ -214,6 +215,7 @@ const makeThrowingMatcher = (
result = matcher.apply(matcherContext, [actual].concat(args));
} catch (error) {
if (
matcher[INTERNAL_MATCHER_FLAG] === true &&
!(error instanceof JestAssertionError) &&
error.name !== 'PrettyFormatPluginError' &&
// Guard for some environments (browsers) that do not support this feature.
Expand Down Expand Up @@ -252,7 +254,8 @@ const makeThrowingMatcher = (
};
};

expect.extend = (matchers: MatchersObject): void => setMatchers(matchers);
expect.extend = (matchers: MatchersObject): void =>
setMatchers(matchers, false);

expect.anything = anything;
expect.any = any;
Expand Down Expand Up @@ -280,9 +283,9 @@ const _validateResult = result => {
};

// add default jest matchers
expect.extend(matchers);
expect.extend(spyMatchers);
expect.extend(toThrowMatchers);
setMatchers(matchers, true);
setMatchers(spyMatchers, true);
setMatchers(toThrowMatchers, true);

expect.addSnapshotSerializer = () => void 0;
expect.assertions = (expected: number) => {
Expand Down
13 changes: 12 additions & 1 deletion packages/expect/src/jest_matchers_object.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import type {MatchersObject} from 'types/Matchers';
// the state, that can hold matcher specific values that change over time.
const JEST_MATCHERS_OBJECT = Symbol.for('$$jest-matchers-object');

// Notes a built-in/internal Jest matcher.
// Jest may override the stack trace of Errors thrown by internal matchers.
export const INTERNAL_MATCHER_FLAG = Symbol.for('$$jest-internal-matcher');

if (!global[JEST_MATCHERS_OBJECT]) {
Object.defineProperty(global, JEST_MATCHERS_OBJECT, {
value: {
Expand All @@ -35,6 +39,13 @@ export const setState = (state: Object) => {

export const getMatchers = () => global[JEST_MATCHERS_OBJECT].matchers;

export const setMatchers = (matchers: MatchersObject) => {
export const setMatchers = (matchers: MatchersObject, isInternal: boolean) => {
Object.keys(matchers).forEach(key => {
const matcher = matchers[key];
Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, {
value: isInternal,
});
});

Object.assign(global[JEST_MATCHERS_OBJECT].matchers, matchers);
};