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: throw useful error on invalid custom matchers #12488

Merged
merged 3 commits into from Feb 24, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -33,6 +33,7 @@
### Fixes

- `[expect]` Move typings of `.not`, `.rejects` and `.resolves` modifiers outside of `Matchers` interface ([#12346](https://github.com/facebook/jest/pull/12346))
- `[expect]` Throw useful error if `expect.extend` is called with invalid matchers ([#12488](https://github.com/facebook/jest/pull/12488))
- `[jest-config]` Correctly detect CI environment and update snapshots accordingly ([#12378](https://github.com/facebook/jest/pull/12378))
- `[jest-config]` Pass `moduleTypes` to `ts-node` to enforce CJS when transpiling ([#12397](https://github.com/facebook/jest/pull/12397))
- `[jest-config, jest-haste-map]` Allow searching for tests in `node_modules` by exposing `retainAllFiles` ([#11084](https://github.com/facebook/jest/pull/11084))
Expand Down
24 changes: 24 additions & 0 deletions packages/expect/src/__tests__/extend.test.ts
Expand Up @@ -184,3 +184,27 @@ it('allows overriding existing extension', () => {

jestExpect('foo').toAllowOverridingExistingMatcher();
});

it('throws descriptive errors for invalid matchers', () => {
expect(() =>
jestExpect.extend({
default: undefined,
}),
).toThrow(
'expect.extend: `default` is not a valid matcher. Must be a function, is "undefined"',
);
expect(() =>
jestExpect.extend({
default: 42,
}),
).toThrow(
'expect.extend: `default` is not a valid matcher. Must be a function, is "number"',
);
expect(() =>
jestExpect.extend({
default: 'foobar',
}),
).toThrow(
'expect.extend: `default` is not a valid matcher. Must be a function, is "string"',
);
});
10 changes: 10 additions & 0 deletions packages/expect/src/jestMatchersObject.ts
Expand Up @@ -6,6 +6,7 @@
*
*/

import {getType} from 'jest-get-type';
import {AsymmetricMatcher} from './asymmetricMatchers';
import type {
Expect,
Expand Down Expand Up @@ -56,6 +57,15 @@ export const setMatchers = (
): void => {
Object.keys(matchers).forEach(key => {
const matcher = matchers[key];

if (typeof matcher !== 'function') {
throw new TypeError(
`expect.extend: \`${key}\` is not a valid matcher. Must be a function, is "${getType(
matcher,
)}"`,
);
}

Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, {
value: isInternal,
});
Expand Down