deno.land / std@0.224.0 / expect / _matchers.ts

_matchers.ts
View Documentation
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { assertNotStrictEquals } from "../assert/assert_not_strict_equals.ts";import { assertStrictEquals } from "../assert/assert_strict_equals.ts";import { assertInstanceOf } from "../assert/assert_instance_of.ts";import { assertIsError } from "../assert/assert_is_error.ts";import { assertNotInstanceOf } from "../assert/assert_not_instance_of.ts";import { assertMatch } from "../assert/assert_match.ts";import { assertObjectMatch } from "../assert/assert_object_match.ts";import { assertNotMatch } from "../assert/assert_not_match.ts";import { AssertionError } from "../assert/assertion_error.ts";
import { assertEquals } from "./_assert_equals.ts";import { assertNotEquals } from "./_assert_not_equals.ts";import { equal } from "./_equal.ts";import { format } from "../internal/format.ts";import type { AnyConstructor, MatcherContext, MatchResult } from "./_types.ts";import { getMockCalls } from "./_mock_util.ts";import { inspectArg, inspectArgs } from "./_inspect_args.ts";import { buildEqualOptions, iterableEquality } from "./_utils.ts";
export function toBe(context: MatcherContext, expect: unknown): MatchResult { if (context.isNot) { assertNotStrictEquals(context.value, expect, context.customMessage); } else { assertStrictEquals(context.value, expect, context.customMessage); }}
export function toEqual( context: MatcherContext, expected: unknown,): MatchResult { const v = context.value; const e = expected; const equalsOptions = buildEqualOptions({ ...context, customTesters: [ ...context.customTesters, iterableEquality, ], });
if (context.isNot) { assertNotEquals(v, e, equalsOptions); } else { assertEquals(v, e, equalsOptions); }}
export function toStrictEqual( context: MatcherContext, expected: unknown,): MatchResult { const equalsOptions = buildEqualOptions({ ...context, strictCheck: true, customTesters: [ ...context.customTesters, iterableEquality, ], });
if (context.isNot) { assertNotEquals(context.value, expected, equalsOptions); } else { assertEquals(context.value, expected, equalsOptions); }}
export function toBeCloseTo( context: MatcherContext, expected: number, numDigits = 2,): MatchResult { if (numDigits < 0) { throw new Error( "toBeCloseTo second argument must be a non-negative integer. Got " + numDigits, ); } const tolerance = 0.5 * Math.pow(10, -numDigits); const value = Number(context.value); const pass = Math.abs(expected - value) < tolerance;
if (context.isNot) { if (pass) { throw new AssertionError( `Expected the value not to be close to ${expected} (using ${numDigits} digits), but it is`, ); } } else { if (!pass) { throw new AssertionError( `Expected the value (${value} to be close to ${expected} (using ${numDigits} digits), but it is not`, ); } }}
export function toBeDefined(context: MatcherContext): MatchResult { if (context.isNot) { assertStrictEquals(context.value, undefined, context.customMessage); } else { assertNotStrictEquals(context.value, undefined, context.customMessage); }}
export function toBeUndefined(context: MatcherContext): MatchResult { if (context.isNot) { assertNotStrictEquals( context.value, undefined, context.customMessage, ); } else { assertStrictEquals(context.value, undefined, context.customMessage); }}
export function toBeFalsy( context: MatcherContext,): MatchResult { const isFalsy = !(context.value); if (context.isNot) { if (isFalsy) { throw new AssertionError( `Expected ${context.value} to NOT be falsy`, ); } } else { if (!isFalsy) { throw new AssertionError( `Expected ${context.value} to be falsy`, ); } }}
export function toBeTruthy( context: MatcherContext,): MatchResult { const isTruthy = !!(context.value); if (context.isNot) { if (isTruthy) { throw new AssertionError( `Expected ${context.value} to NOT be truthy`, ); } } else { if (!isTruthy) { throw new AssertionError( `Expected ${context.value} to be truthy`, ); } }}
export function toBeGreaterThanOrEqual( context: MatcherContext, expected: number,): MatchResult { const isGreaterOrEqual = Number(context.value) >= Number(expected); if (context.isNot) { if (isGreaterOrEqual) { throw new AssertionError( `Expected ${context.value} to NOT be greater than or equal ${expected}`, ); } } else { if (!isGreaterOrEqual) { throw new AssertionError( `Expected ${context.value} to be greater than or equal ${expected}`, ); } }}
export function toBeGreaterThan( context: MatcherContext, expected: number,): MatchResult { const isGreater = Number(context.value) > Number(expected); if (context.isNot) { if (isGreater) { throw new AssertionError( `Expected ${context.value} to NOT be greater than ${expected}`, ); } } else { if (!isGreater) { throw new AssertionError( `Expected ${context.value} to be greater than ${expected}`, ); } }}
export function toBeInstanceOf<T extends AnyConstructor>( context: MatcherContext, expected: T,): MatchResult { if (context.isNot) { assertNotInstanceOf(context.value, expected); } else { assertInstanceOf(context.value, expected); }}export function toBeLessThanOrEqual( context: MatcherContext, expected: number,): MatchResult { const isLower = Number(context.value) <= Number(expected); if (context.isNot) { if (isLower) { throw new AssertionError( `Expected ${context.value} to NOT be lower than or equal ${expected}`, ); } } else { if (!isLower) { throw new AssertionError( `Expected ${context.value} to be lower than or equal ${expected}`, ); } }}export function toBeLessThan( context: MatcherContext, expected: number,): MatchResult { const isLower = Number(context.value) < Number(expected); if (context.isNot) { if (isLower) { throw new AssertionError( `Expected ${context.value} to NOT be lower than ${expected}`, ); } } else { if (!isLower) { throw new AssertionError( `Expected ${context.value} to be lower than ${expected}`, ); } }}export function toBeNaN(context: MatcherContext): MatchResult { const equalsOptions = buildEqualOptions(context); if (context.isNot) { assertNotEquals( isNaN(Number(context.value)), true, { ...equalsOptions, msg: equalsOptions.msg || `Expected ${context.value} to not be NaN`, }, ); } else { assertEquals( isNaN(Number(context.value)), true, { ...equalsOptions, msg: equalsOptions.msg || `Expected ${context.value} to be NaN`, }, ); }}
export function toBeNull(context: MatcherContext): MatchResult { if (context.isNot) { assertNotStrictEquals( context.value as number, null, context.customMessage || `Expected ${context.value} to not be null`, ); } else { assertStrictEquals( context.value as number, null, context.customMessage || `Expected ${context.value} to be null`, ); }}
export function toHaveLength( context: MatcherContext, expected: number,): MatchResult { const { value } = context; // deno-lint-ignore no-explicit-any const maybeLength = (value as any)?.length; const hasLength = maybeLength === expected;
if (context.isNot) { if (hasLength) { throw new AssertionError( `Expected value not to have length ${expected}, but it does`, ); } } else { if (!hasLength) { throw new AssertionError( `Expected value to have length ${expected}, but it does not. (The value has length ${maybeLength})`, ); } }}
export function toHaveProperty( context: MatcherContext, propName: string | string[], v?: unknown,): MatchResult { const { value } = context;
let propPath = [] as string[]; if (Array.isArray(propName)) { propPath = propName; } else { propPath = propName.split("."); }
// deno-lint-ignore no-explicit-any let current = value as any; while (true) { if (current === undefined || current === null) { break; } if (propPath.length === 0) { break; } const prop = propPath.shift()!; current = current[prop]; }
let hasProperty; if (v) { hasProperty = current !== undefined && propPath.length === 0 && equal(current, v, context); } else { hasProperty = current !== undefined && propPath.length === 0; }
let ofValue = ""; if (v) { ofValue = ` of the value ${inspectArg(v)}`; }
if (context.isNot) { if (hasProperty) { throw new AssertionError( `Expected the value not to have the property ${ propPath.join(".") }${ofValue}, but it does.`, ); } } else { if (!hasProperty) { throw new AssertionError( `Expected the value to have the property ${ propPath.join(".") }${ofValue}, but it does not.`, ); } }}
export function toContain( context: MatcherContext, expected: unknown,): MatchResult { // deno-lint-ignore no-explicit-any const doesContain = (context.value as any)?.includes?.(expected);
if (context.isNot) { if (doesContain) { throw new AssertionError("The value contains the expected item"); } } else { if (!doesContain) { throw new AssertionError("The value doesn't contain the expected item"); } }}
export function toContainEqual( context: MatcherContext, expected: unknown,): MatchResult { const { value } = context; assertIsIterable(value); let doesContain = false;
for (const item of value) { if (equal(item, expected, context)) { doesContain = true; break; } }
if (context.isNot) { if (doesContain) { throw new AssertionError("The value contains the expected item"); } } else { if (!doesContain) { throw new AssertionError("The value doesn't contain the expected item"); } }}
// deno-lint-ignore no-explicit-anyfunction assertIsIterable(value: any): asserts value is Iterable<unknown> { if (value == null) { throw new AssertionError("The value is null or undefined"); } if (typeof value[Symbol.iterator] !== "function") { throw new AssertionError("The value is not iterable"); }}
export function toMatch( context: MatcherContext, expected: RegExp,): MatchResult { if (context.isNot) { assertNotMatch( String(context.value), expected, context.customMessage, ); } else { assertMatch(String(context.value), expected, context.customMessage); }}
export function toMatchObject( context: MatcherContext, expected: Record<PropertyKey, unknown> | Record<PropertyKey, unknown>[],): MatchResult { if (context.isNot) { let objectMatch = false; try { assertObjectMatch( // deno-lint-ignore no-explicit-any context.value as Record<PropertyKey, any>, expected as Record<PropertyKey, unknown>, context.customMessage, ); objectMatch = true; const actualString = format(context.value); const expectedString = format(expected); throw new AssertionError( `Expected ${actualString} to NOT match ${expectedString}`, ); } catch (e) { if (objectMatch) { throw e; } return; } } else { assertObjectMatch( // deno-lint-ignore no-explicit-any context.value as Record<PropertyKey, any>, expected as Record<PropertyKey, unknown>, context.customMessage, ); }}
export function toHaveBeenCalled(context: MatcherContext): MatchResult { const calls = getMockCalls(context.value); const hasBeenCalled = calls.length > 0;
if (context.isNot) { if (hasBeenCalled) { throw new AssertionError( `Expected mock function not to be called, but it was called ${calls.length} time(s)`, ); } } else { if (!hasBeenCalled) { throw new AssertionError( `Expected mock function to be called, but it was not called`, ); } }}
export function toHaveBeenCalledTimes( context: MatcherContext, expected: number,): MatchResult { const calls = getMockCalls(context.value);
if (context.isNot) { if (calls.length === expected) { throw new AssertionError( `Expected mock function not to be called ${expected} time(s), but it was`, ); } } else { if (calls.length !== expected) { throw new AssertionError( `Expected mock function to be called ${expected} time(s), but it was called ${calls.length} time(s)`, ); } }}
export function toHaveBeenCalledWith( context: MatcherContext, ...expected: unknown[]): MatchResult { const calls = getMockCalls(context.value); const hasBeenCalled = calls.some((call) => equal(call.args, expected));
if (context.isNot) { if (hasBeenCalled) { throw new AssertionError( `Expected mock function not to be called with ${ inspectArgs(expected) }, but it was`, ); } } else { if (!hasBeenCalled) { let otherCalls = ""; if (calls.length > 0) { otherCalls = `\n Other calls:\n ${ calls.map((call) => inspectArgs(call.args)).join("\n ") }`; } throw new AssertionError( `Expected mock function to be called with ${ inspectArgs(expected) }, but it was not.${otherCalls}`, ); } }}export function toHaveBeenLastCalledWith( context: MatcherContext, ...expected: unknown[]): MatchResult { const calls = getMockCalls(context.value); const hasBeenCalled = calls.length > 0 && equal(calls.at(-1)?.args, expected);
if (context.isNot) { if (hasBeenCalled) { throw new AssertionError( `Expected mock function not to be last called with ${ inspectArgs(expected) }, but it was`, ); } } else { if (!hasBeenCalled) { const lastCall = calls.at(-1); if (!lastCall) { throw new AssertionError( `Expected mock function to be last called with ${ inspectArgs(expected) }, but it was not.`, ); } else { throw new AssertionError( `Expected mock function to be last called with ${ inspectArgs(expected) }, but it was last called with ${inspectArgs(lastCall.args)}.`, ); } } }}export function toHaveBeenNthCalledWith( context: MatcherContext, nth: number, ...expected: unknown[]): MatchResult { if (nth < 1) { new Error(`nth must be greater than 0. ${nth} was given.`); }
const calls = getMockCalls(context.value); const callIndex = nth - 1; const hasBeenCalled = calls.length > callIndex && equal(calls[callIndex]?.args, expected);
if (context.isNot) { if (hasBeenCalled) { throw new AssertionError( `Expected the n-th call (n=${nth}) of mock function is not with ${ inspectArgs(expected) }, but it was`, ); } } else { if (!hasBeenCalled) { const nthCall = calls[callIndex]; if (!nthCall) { throw new AssertionError( `Expected the n-th call (n=${nth}) of mock function is with ${ inspectArgs(expected) }, but the n-th call does not exist.`, ); } else { throw new AssertionError( `Expected the n-th call (n=${nth}) of mock function is with ${ inspectArgs(expected) }, but it was with ${inspectArgs(nthCall.args)}.`, ); } } }}
export function toHaveReturned(context: MatcherContext): MatchResult { const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns);
if (context.isNot) { if (returned.length > 0) { throw new AssertionError( `Expected the mock function to not have returned, but it returned ${returned.length} times`, ); } } else { if (returned.length === 0) { throw new AssertionError( `Expected the mock function to have returned, but it did not return`, ); } }}
export function toHaveReturnedTimes( context: MatcherContext, expected: number,): MatchResult { const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns);
if (context.isNot) { if (returned.length === expected) { throw new AssertionError( `Expected the mock function to not have returned ${expected} times, but it returned ${returned.length} times`, ); } } else { if (returned.length !== expected) { throw new AssertionError( `Expected the mock function to have returned ${expected} times, but it returned ${returned.length} times`, ); } }}export function toHaveReturnedWith( context: MatcherContext, expected: unknown,): MatchResult { const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns); const returnedWithExpected = returned.some((call) => equal(call.returned, expected) );
if (context.isNot) { if (returnedWithExpected) { throw new AssertionError( `Expected the mock function to not have returned with ${ inspectArg(expected) }, but it did`, ); } } else { if (!returnedWithExpected) { throw new AssertionError( `Expected the mock function to have returned with ${ inspectArg(expected) }, but it did not`, ); } }}
export function toHaveLastReturnedWith( context: MatcherContext, expected: unknown,): MatchResult { const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns); const lastReturnedWithExpected = returned.length > 0 && equal(returned.at(-1)?.returned, expected);
if (context.isNot) { if (lastReturnedWithExpected) { throw new AssertionError( `Expected the mock function to not have last returned with ${ inspectArg(expected) }, but it did`, ); } } else { if (!lastReturnedWithExpected) { throw new AssertionError( `Expected the mock function to have last returned with ${ inspectArg(expected) }, but it did not`, ); } }}
export function toHaveNthReturnedWith( context: MatcherContext, nth: number, expected: unknown,): MatchResult { if (nth < 1) { throw new Error(`nth(${nth}) must be greater than 0`); }
const calls = getMockCalls(context.value); const returned = calls.filter((call) => call.returns); const returnIndex = nth - 1; const maybeNthReturned = returned[returnIndex]; const nthReturnedWithExpected = maybeNthReturned && equal(maybeNthReturned.returned, expected);
if (context.isNot) { if (nthReturnedWithExpected) { throw new AssertionError( `Expected the mock function to not have n-th (n=${nth}) returned with ${ inspectArg(expected) }, but it did`, ); } } else { if (!nthReturnedWithExpected) { throw new AssertionError( `Expected the mock function to have n-th (n=${nth}) returned with ${ inspectArg(expected) }, but it did not`, ); } }}
export function toThrow<E extends Error = Error>( context: MatcherContext, // deno-lint-ignore no-explicit-any expected?: string | RegExp | E | (new (...args: any[]) => E),): MatchResult { if (typeof context.value === "function") { try { context.value = context.value(); } catch (err) { context.value = err; } }
// deno-lint-ignore no-explicit-any type ErrorClass = new (...args: any[]) => Error; let expectClass: undefined | ErrorClass = undefined; let expectMessage: undefined | string | RegExp = undefined; if (expected instanceof Error) { expectClass = expected.constructor as ErrorClass; expectMessage = expected.message; } if (expected instanceof Function) { expectClass = expected as ErrorClass; } if (typeof expected === "string" || expected instanceof RegExp) { expectMessage = expected; }
if (context.isNot) { let isError = false; try { assertIsError( context.value, expectClass, expectMessage, context.customMessage, ); isError = true; throw new AssertionError(`Expected to NOT throw ${expected}`); } catch (e) { if (isError) { throw e; } return; } } return assertIsError( context.value, expectClass, expectMessage, context.customMessage, );}
std

Version Info

Tagged at
6 months ago