Skip to content

Commit

Permalink
fix: throw useful error on invalid custom matchers (#12488)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored Feb 24, 2022
1 parent d0d7dab commit 87fcd89
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 87fcd89

Please sign in to comment.