|
7 | 7 | * @flow |
8 | 8 | */ |
9 | 9 |
|
10 | | -import type {MatchersObject} from 'types/Matchers'; |
| 10 | +import {AsymmetricMatcher} from './asymmetric_matchers'; |
| 11 | +import type {Expect, MatchersObject} from 'types/Matchers'; |
11 | 12 |
|
12 | 13 | // Global matchers object holds the list of available matchers and |
13 | 14 | // the state, that can hold matcher specific values that change over time. |
@@ -39,12 +40,57 @@ export const setState = (state: Object) => { |
39 | 40 |
|
40 | 41 | export const getMatchers = () => global[JEST_MATCHERS_OBJECT].matchers; |
41 | 42 |
|
42 | | -export const setMatchers = (matchers: MatchersObject, isInternal: boolean) => { |
| 43 | +export const setMatchers = ( |
| 44 | + matchers: MatchersObject, |
| 45 | + isInternal: boolean, |
| 46 | + expect: Expect, |
| 47 | +) => { |
43 | 48 | Object.keys(matchers).forEach(key => { |
44 | 49 | const matcher = matchers[key]; |
45 | 50 | Object.defineProperty(matcher, INTERNAL_MATCHER_FLAG, { |
46 | 51 | value: isInternal, |
47 | 52 | }); |
| 53 | + |
| 54 | + if (!isInternal) { |
| 55 | + // expect is defined |
| 56 | + |
| 57 | + class CustomMatcher extends AsymmetricMatcher { |
| 58 | + sample: any; |
| 59 | + |
| 60 | + constructor(sample: any, inverse: boolean = false) { |
| 61 | + super(); |
| 62 | + this.sample = sample; |
| 63 | + this.inverse = inverse; |
| 64 | + } |
| 65 | + |
| 66 | + asymmetricMatch(other: any) { |
| 67 | + const {pass}: {message: () => string, pass: boolean} = matcher( |
| 68 | + (other: any), |
| 69 | + (this.sample: any), |
| 70 | + ); |
| 71 | + |
| 72 | + return this.inverse ? !pass : pass; |
| 73 | + } |
| 74 | + |
| 75 | + toString() { |
| 76 | + return `${this.inverse ? 'not.' : ''}${key}`; |
| 77 | + } |
| 78 | + |
| 79 | + getExpectedType() { |
| 80 | + return 'any'; |
| 81 | + } |
| 82 | + |
| 83 | + toAsymmetricMatcher() { |
| 84 | + return `${this.toString()}<${this.sample}>`; |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + expect[key] = (sample: any) => new CustomMatcher(sample); |
| 89 | + if (!expect.not) { |
| 90 | + expect.not = {}; |
| 91 | + } |
| 92 | + expect.not[key] = (sample: any) => new CustomMatcher(sample, true); |
| 93 | + } |
48 | 94 | }); |
49 | 95 |
|
50 | 96 | Object.assign(global[JEST_MATCHERS_OBJECT].matchers, matchers); |
|
0 commit comments