-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
459 lines (409 loc) · 12.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/* eslint-disable local/prefer-spread-eventually */
import {equals, iterableEquality, subsetEquality} from '@jest/expect-utils';
import * as matcherUtils from 'jest-matcher-utils';
import {ErrorWithStack, isPromise} from 'jest-util';
import {
any,
anything,
arrayContaining,
arrayNotContaining,
closeTo,
notCloseTo,
objectContaining,
objectNotContaining,
stringContaining,
stringMatching,
stringNotContaining,
stringNotMatching,
} from './asymmetricMatchers';
import extractExpectedAssertionsErrors from './extractExpectedAssertionsErrors';
import {
INTERNAL_MATCHER_FLAG,
addCustomEqualityTesters,
getCustomEqualityTesters,
getMatchers,
getState,
setMatchers,
setState,
} from './jestMatchersObject';
import matchers from './matchers';
import spyMatchers from './spyMatchers';
import toThrowMatchers, {
createMatcher as createThrowMatcher,
} from './toThrowMatchers';
import type {
Expect,
ExpectationResult,
MatcherContext,
MatcherState,
MatcherUtils,
MatchersObject,
PromiseMatcherFn,
RawMatcherFn,
SyncExpectationResult,
ThrowingMatcherFn,
} from './types';
export type {Tester, TesterContext} from '@jest/expect-utils';
export {AsymmetricMatcher} from './asymmetricMatchers';
export type {
AsyncExpectationResult,
AsymmetricMatchers,
BaseExpect,
Expect,
ExpectationResult,
MatcherContext,
MatcherFunction,
MatcherFunctionWithContext,
MatcherState,
MatcherUtils,
Matchers,
SyncExpectationResult,
} from './types';
export class JestAssertionError extends Error {
matcherResult?: Omit<SyncExpectationResult, 'message'> & {message: string};
}
const createToThrowErrorMatchingSnapshotMatcher = function (
matcher: RawMatcherFn,
) {
return function (
this: MatcherContext,
received: any,
testNameOrInlineSnapshot?: string,
) {
return matcher.apply(this, [received, testNameOrInlineSnapshot, true]);
};
};
const getPromiseMatcher = (name: string, matcher: RawMatcherFn) => {
if (name === 'toThrow') {
return createThrowMatcher(name, true);
} else if (
name === 'toThrowErrorMatchingSnapshot' ||
name === 'toThrowErrorMatchingInlineSnapshot'
) {
return createToThrowErrorMatchingSnapshotMatcher(matcher);
}
return null;
};
export const expect: Expect = (actual: any, ...rest: Array<any>) => {
if (rest.length > 0) {
throw new Error('Expect takes at most one argument.');
}
const allMatchers = getMatchers();
const expectation: any = {
not: {},
rejects: {not: {}},
resolves: {not: {}},
};
const err = new JestAssertionError();
for (const name of Object.keys(allMatchers)) {
const matcher = allMatchers[name];
const promiseMatcher = getPromiseMatcher(name, matcher) || matcher;
expectation[name] = makeThrowingMatcher(matcher, false, '', actual);
expectation.not[name] = makeThrowingMatcher(matcher, true, '', actual);
expectation.resolves[name] = makeResolveMatcher(
name,
promiseMatcher,
false,
actual,
err,
);
expectation.resolves.not[name] = makeResolveMatcher(
name,
promiseMatcher,
true,
actual,
err,
);
expectation.rejects[name] = makeRejectMatcher(
name,
promiseMatcher,
false,
actual,
err,
);
expectation.rejects.not[name] = makeRejectMatcher(
name,
promiseMatcher,
true,
actual,
err,
);
}
return expectation;
};
const getMessage = (message?: () => string) =>
(message && message()) ||
matcherUtils.RECEIVED_COLOR('No message was specified for this matcher.');
const makeResolveMatcher =
(
matcherName: string,
matcher: RawMatcherFn,
isNot: boolean,
actual: Promise<any>,
outerErr: JestAssertionError,
): PromiseMatcherFn =>
(...args) => {
const options = {
isNot,
promise: 'resolves',
};
if (!isPromise(actual)) {
throw new JestAssertionError(
matcherUtils.matcherErrorMessage(
matcherUtils.matcherHint(matcherName, undefined, '', options),
`${matcherUtils.RECEIVED_COLOR('received')} value must be a promise`,
matcherUtils.printWithType(
'Received',
actual,
matcherUtils.printReceived,
),
),
);
}
const innerErr = new JestAssertionError();
return actual.then(
result =>
makeThrowingMatcher(matcher, isNot, 'resolves', result, innerErr).apply(
null,
args,
),
error => {
outerErr.message =
`${matcherUtils.matcherHint(
matcherName,
undefined,
'',
options,
)}\n\n` +
'Received promise rejected instead of resolved\n' +
`Rejected to value: ${matcherUtils.printReceived(error)}`;
throw outerErr;
},
);
};
const makeRejectMatcher =
(
matcherName: string,
matcher: RawMatcherFn,
isNot: boolean,
actual: Promise<any> | (() => Promise<any>),
outerErr: JestAssertionError,
): PromiseMatcherFn =>
(...args) => {
const options = {
isNot,
promise: 'rejects',
};
const actualWrapper: Promise<any> =
typeof actual === 'function' ? actual() : actual;
if (!isPromise(actualWrapper)) {
throw new JestAssertionError(
matcherUtils.matcherErrorMessage(
matcherUtils.matcherHint(matcherName, undefined, '', options),
`${matcherUtils.RECEIVED_COLOR(
'received',
)} value must be a promise or a function returning a promise`,
matcherUtils.printWithType(
'Received',
actual,
matcherUtils.printReceived,
),
),
);
}
const innerErr = new JestAssertionError();
return actualWrapper.then(
result => {
outerErr.message =
`${matcherUtils.matcherHint(
matcherName,
undefined,
'',
options,
)}\n\n` +
'Received promise resolved instead of rejected\n' +
`Resolved to value: ${matcherUtils.printReceived(result)}`;
throw outerErr;
},
error =>
makeThrowingMatcher(matcher, isNot, 'rejects', error, innerErr).apply(
null,
args,
),
);
};
const makeThrowingMatcher = (
matcher: RawMatcherFn,
isNot: boolean,
promise: string,
actual: any,
err?: JestAssertionError,
): ThrowingMatcherFn =>
function throwingMatcher(...args): any {
let throws = true;
const utils: MatcherUtils['utils'] = {
...matcherUtils,
iterableEquality,
subsetEquality,
};
const matcherUtilsThing: MatcherUtils = {
customTesters: getCustomEqualityTesters(),
// When throws is disabled, the matcher will not throw errors during test
// execution but instead add them to the global matcher state. If a
// matcher throws, test execution is normally stopped immediately. The
// snapshot matcher uses it because we want to log all snapshot
// failures in a test.
dontThrow: () => (throws = false),
equals,
utils,
};
const matcherContext: MatcherContext = {
...getState<MatcherState>(),
...matcherUtilsThing,
error: err,
isNot,
promise,
};
const processResult = (
result: SyncExpectationResult,
asyncError?: JestAssertionError,
) => {
_validateResult(result);
getState().assertionCalls++;
if ((result.pass && isNot) || (!result.pass && !isNot)) {
// XOR
const message = getMessage(result.message);
let error;
if (err) {
error = err;
error.message = message;
} else if (asyncError) {
error = asyncError;
error.message = message;
} else {
error = new JestAssertionError(message);
// Try to remove this function from the stack trace frame.
// Guard for some environments (browsers) that do not support this feature.
if (Error.captureStackTrace) {
Error.captureStackTrace(error, throwingMatcher);
}
}
// Passing the result of the matcher with the error so that a custom
// reporter could access the actual and expected objects of the result
// for example in order to display a custom visual diff
error.matcherResult = {...result, message};
if (throws) {
throw error;
} else {
getState().suppressedErrors.push(error);
}
} else {
getState().numPassingAsserts++;
}
};
const handleError = (error: Error) => {
if (
matcher[INTERNAL_MATCHER_FLAG] === true &&
!(error instanceof JestAssertionError) &&
error.name !== 'PrettyFormatPluginError' &&
// Guard for some environments (browsers) that do not support this feature.
Error.captureStackTrace
) {
// Try to remove this and deeper functions from the stack trace frame.
Error.captureStackTrace(error, throwingMatcher);
}
throw error;
};
let potentialResult: ExpectationResult;
try {
potentialResult =
matcher[INTERNAL_MATCHER_FLAG] === true
? matcher.call(matcherContext, actual, ...args)
: // It's a trap specifically for inline snapshot to capture this name
// in the stack trace, so that it can correctly get the custom matcher
// function call.
(function __EXTERNAL_MATCHER_TRAP__() {
return matcher.call(matcherContext, actual, ...args);
})();
if (isPromise(potentialResult)) {
const asyncError = new JestAssertionError();
if (Error.captureStackTrace) {
Error.captureStackTrace(asyncError, throwingMatcher);
}
return potentialResult
.then(aResult => processResult(aResult, asyncError))
.catch(handleError);
} else {
return processResult(potentialResult);
}
} catch (error: any) {
return handleError(error);
}
};
expect.extend = (matchers: MatchersObject) =>
setMatchers(matchers, false, expect);
expect.addEqualityTesters = customTesters =>
addCustomEqualityTesters(customTesters);
expect.anything = anything;
expect.any = any;
expect.not = {
arrayContaining: arrayNotContaining,
closeTo: notCloseTo,
objectContaining: objectNotContaining,
stringContaining: stringNotContaining,
stringMatching: stringNotMatching,
};
expect.arrayContaining = arrayContaining;
expect.closeTo = closeTo;
expect.objectContaining = objectContaining;
expect.stringContaining = stringContaining;
expect.stringMatching = stringMatching;
const _validateResult = (result: any) => {
if (
typeof result !== 'object' ||
typeof result.pass !== 'boolean' ||
(result.message &&
typeof result.message !== 'string' &&
typeof result.message !== 'function')
) {
throw new Error(
'Unexpected return from a matcher function.\n' +
'Matcher functions should ' +
'return an object in the following format:\n' +
' {message?: string | function, pass: boolean}\n' +
`'${matcherUtils.stringify(result)}' was returned`,
);
}
};
function assertions(expected: number): void {
const error = new ErrorWithStack(undefined, assertions);
setState({
expectedAssertionsNumber: expected,
expectedAssertionsNumberError: error,
});
}
function hasAssertions(...args: Array<unknown>): void {
const error = new ErrorWithStack(undefined, hasAssertions);
matcherUtils.ensureNoExpected(args[0], '.hasAssertions');
setState({
isExpectingAssertions: true,
isExpectingAssertionsError: error,
});
}
// add default jest matchers
setMatchers(matchers, true, expect);
setMatchers(spyMatchers, true, expect);
setMatchers(toThrowMatchers, true, expect);
expect.assertions = assertions;
expect.hasAssertions = hasAssertions;
expect.getState = getState;
expect.setState = setState;
expect.extractExpectedAssertionsErrors = extractExpectedAssertionsErrors;
export default expect;