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

Make rejects and resolves synchronously validate its argument #5364

Merged
merged 9 commits into from
Jan 24, 2018
12 changes: 12 additions & 0 deletions packages/expect/src/__tests__/matchers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ describe('.rejects', () => {
await jestExpect(fn()).rejects.toThrow('some error');
});

[4, [1], {a: 1}, 'a', true, null, undefined, () => {}].forEach(value => {
it(`fails non-promise value ${stringify(value)} synchronously`, () => {
let error;
try {
jestExpect(value).rejects.toBe(111);
} catch (e) {
error = e;
}
expect(error).toBeDefined();
});
});

[4, [1], {a: 1}, 'a', true, null, undefined, () => {}].forEach(value => {
it(`fails non-promise value ${stringify(value)}`, async () => {
let error;
Expand Down
30 changes: 16 additions & 14 deletions packages/expect/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const makeRejectMatcher = (
matcher: RawMatcherFn,
isNot: boolean,
actual: Promise<any>,
): PromiseMatcherFn => async (...args) => {
): PromiseMatcherFn => (...args) => {
const matcherStatement = `.rejects.${isNot ? 'not.' : ''}${matcherName}`;
if (!isPromise(actual)) {
throw new JestAssertionError(
Expand All @@ -172,20 +172,22 @@ const makeRejectMatcher = (
);
}

let result;
try {
result = await actual;
} catch (e) {
return makeThrowingMatcher(matcher, isNot, e).apply(null, args);
}
return (async () => {
Copy link
Member

Choose a reason for hiding this comment

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

you can do

return result
.catch(e => makeThrowingMatcher(matcher, isNot, e).apply(null, args))
.then(() => Promise.reject(
  // new JestAssertionError(...
));

And drop the async

let result;
try {
result = await actual;
} catch (e) {
return makeThrowingMatcher(matcher, isNot, e).apply(null, args);
}

throw new JestAssertionError(
utils.matcherHint(matcherStatement, 'received', '') +
'\n\n' +
`Expected ${utils.RECEIVED_COLOR('received')} Promise to reject, ` +
'instead it resolved to value\n' +
` ${utils.printReceived(result)}`,
);
throw new JestAssertionError(
utils.matcherHint(matcherStatement, 'received', '') +
'\n\n' +
`Expected ${utils.RECEIVED_COLOR('received')} Promise to reject, ` +
'instead it resolved to value\n' +
` ${utils.printReceived(result)}`,
);
})();
};

const makeThrowingMatcher = (
Expand Down