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

fix .toThrow for promises #4884

Merged
merged 4 commits into from
Nov 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -2,6 +2,8 @@

### Fixes

* `[expect]` fix .toThrow for promises
([#4884](https://github.com/facebook/jest/pull/4884))
* `[jest-docblock]` pragmas should preserve urls
([#4837](https://github.com/facebook/jest/pull/4629))
* `[jest-cli]` Check if `npm_lifecycle_script` calls Jest directly
Expand Down
4 changes: 2 additions & 2 deletions docs/ExpectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,15 +416,15 @@ For example, this code tests that the promise rejects with reason `'octopus'`:
```js
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject('octopus')).rejects.toBe('octopus');
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
Copy link
Member

Choose a reason for hiding this comment

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

This old example is still valid, right?

Copy link
Member

Choose a reason for hiding this comment

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

(although it's not recommended to reject with a non-error)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, it still works

});
```

Alternatively, you can use `async/await` in combination with `.rejects`.

```js
test('rejects to octopus', async () => {
await expect(Promise.reject('octopus')).rejects.toBe('octopus');
await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
Copy link
Member

Choose a reason for hiding this comment

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

I'm wondering if we should say that toThrow only works in jest 21.3.0+. People copy-paste examples, and having them not working is not a good UX

Copy link
Contributor Author

Choose a reason for hiding this comment

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

currently, it mentions

### `.rejects`

##### available in Jest **20.0.0+**

Change it to 21.3.0+?

Copy link
Member

Choose a reason for hiding this comment

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

Or a separate line describing rejecting promises and toThrow.

Copy link
Member

Choose a reason for hiding this comment

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

@lsentkiewicz this came up in #4945, mind sending a PR with clarification? 🙂

Choose a reason for hiding this comment

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

really painful way to discover why rejects.toThrow was not working on my [email protected] setup

@SimenB you were right, it is probably a good idea to have a mention to it in the docs

Copy link
Member

Choose a reason for hiding this comment

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

Can you send a PR fixing the docs?

});
```

Expand Down
13 changes: 8 additions & 5 deletions packages/expect/src/__tests__/matchers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ describe('.rejects', () => {
await jestExpect(Promise.reject({a: 1, b: 2})).rejects.not.toMatchObject({
c: 1,
});
await jestExpect(
Promise.reject(() => {
throw new Error();
}),
).rejects.toThrow();
await jestExpect(Promise.reject(new Error())).rejects.toThrow();
});

it('should reject with toThrow', async () => {
async function fn() {
throw new Error('some error');
}
await jestExpect(fn()).rejects.toThrow('some error');
});

[4, [1], {a: 1}, 'a', true, null, undefined, () => {}].forEach(value => {
Expand Down
29 changes: 18 additions & 11 deletions packages/expect/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import type {
import * as utils from 'jest-matcher-utils';
import matchers from './matchers';
import spyMatchers from './spy_matchers';
import toThrowMatchers from './to_throw_matchers';
import toThrowMatchers, {
createMatcher as createThrowMatcher,
} from './to_throw_matchers';
import {equals} from './jasmine_utils';
import {
any,
Expand Down Expand Up @@ -51,6 +53,13 @@ const isPromise = obj => {
);
};

const getPromiseMatcher = name => {
if (name === 'toThrow' || name === 'toThrowError') {
return createThrowMatcher('.' + name, true);
}
return null;
};

const expect = (actual: any, ...rest): ExpectationObject => {
if (rest.length !== 0) {
throw new Error('Expect takes at most one argument.');
Expand All @@ -64,35 +73,33 @@ const expect = (actual: any, ...rest): ExpectationObject => {
};

Object.keys(allMatchers).forEach(name => {
expectation[name] = makeThrowingMatcher(allMatchers[name], false, actual);
expectation.not[name] = makeThrowingMatcher(
allMatchers[name],
true,
actual,
);
const matcher = allMatchers[name];
const promiseMatcher = getPromiseMatcher(name) || matcher;
expectation[name] = makeThrowingMatcher(matcher, false, actual);
expectation.not[name] = makeThrowingMatcher(matcher, true, actual);

expectation.resolves[name] = makeResolveMatcher(
name,
allMatchers[name],
promiseMatcher,
false,
actual,
);
expectation.resolves.not[name] = makeResolveMatcher(
name,
allMatchers[name],
promiseMatcher,
true,
actual,
);

expectation.rejects[name] = makeRejectMatcher(
name,
allMatchers[name],
promiseMatcher,
false,
actual,
);
expectation.rejects.not[name] = makeRejectMatcher(
name,
allMatchers[name],
matcher,
true,
actual,
);
Expand Down
31 changes: 17 additions & 14 deletions packages/expect/src/to_throw_matchers.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,29 @@ import {
} from 'jest-matcher-utils';
import {equals} from './jasmine_utils';

const createMatcher = matcherName => (
export const createMatcher = (matcherName: string, fromPromise?: boolean) => (
actual: Function,
expected: string | Error | RegExp,
) => {
const value = expected;
let error;

if (typeof actual !== 'function') {
throw new Error(
matcherHint(matcherName, 'function', getType(value)) +
'\n\n' +
'Received value must be a function, but instead ' +
`"${getType(actual)}" was found`,
);
}

try {
actual();
} catch (e) {
error = e;
if (fromPromise) {
error = actual;
} else {
if (typeof actual !== 'function') {
throw new Error(
matcherHint(matcherName, 'function', getType(value)) +
'\n\n' +
'Received value must be a function, but instead ' +
`"${getType(actual)}" was found`,
);
}
try {
actual();
} catch (e) {
error = e;
}
}

if (typeof expected === 'string') {
Expand Down