-
-
Notifications
You must be signed in to change notification settings - Fork 269
/
index.ts
1162 lines (1093 loc) · 31.9 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
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Extra,
extraFromError,
MessageExtra,
normalizeMessageExtra,
TapPlugin,
TestBase,
} from '@tapjs/core'
import * as stack from '@tapjs/stack'
import EventEmitter from 'events'
import { isPromise } from 'is-actual-promise'
import {
CompareOptions,
has,
hasStrict,
match,
matchOnly,
matchOnlyStrict,
matchStrict,
same,
strict,
} from 'tcompare'
import { Deferred } from 'trivial-deferred'
export interface AssertOptions {
compareOptions?: CompareOptions
}
import { normalizeThrowsArgs } from './normalize-throws-args.js'
export type ErrorMessageMatch = {
message: string | RegExp
[k: string]: any
}
export type ErrorNameMatch = {
name: string | RegExp | null | undefined
[k: string]: any
}
export type ErrorCodeMatch = {
code: string | RegExp | number | null | undefined
[k: string]: any
}
export type ErrorCauseMatch = {
cause: any
[k: string]: any
}
export type ErrorMatch =
| Error
| typeof Error
| ErrorMessageMatch
| ErrorNameMatch
| ErrorCodeMatch
| ErrorCauseMatch
| RegExp
export type ThrowsArgs =
| []
| [msg: string, extra?: Extra]
| [wanted: ErrorMatch, ...messageExtra: MessageExtra]
export type ExpectedEmit = [
emitted: boolean,
emitter: EventEmitter | EventTarget,
event: string,
handler: (...a: any) => void,
msg: string,
extra: Extra
]
// return true of every argument is an object
const objects = (...a: any[]): boolean =>
!a.some(o => !o || typeof o !== 'object')
const hasOwn = <T extends {}>(
obj: T,
key: string | number | symbol
) => Object.prototype.hasOwnProperty.call(obj, key)
export class Assertions {
#t: TestBase
#opts: CompareOptions
#pendingEmits: ExpectedEmit[] = []
#setOnBeforeEnd: boolean = false
constructor(t: TestBase, { compareOptions }: AssertOptions) {
this.#t = t
// TODO: this is a pita to do in each plugin
// Either there should be a straightforward interface for declaring
// which fields get inherited, or maybe add some logic in TestBase
// to inherit all but the select few that can't be.
if (!compareOptions) {
for (let p = t.parent; p && !compareOptions; p = p.parent) {
compareOptions = p.options.compareOptions
}
if (compareOptions) t.options.compareOptions = compareOptions
}
this.#opts = compareOptions || {}
}
#onBeforeEnd() {
for (const [emitted, emitter, event, handler, msg, extra] of this
.#pendingEmits) {
if (emitted) {
this.#t.pass(msg, extra)
} else {
if (emitter instanceof EventEmitter) {
emitter.removeListener(event, handler)
} else {
emitter.removeEventListener(event, handler)
}
this.#t.fail(msg, extra)
}
}
}
/**
* Verify that the value is truthy
*
* @group Assertion Methods
*/
ok(obj: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.ok
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should be equal', args)
return obj ? this.#t.pass(...me) : this.#t.fail(...me)
}
/**
* Verify that the value is not truthy
*
* @group Assertion Methods
*/
notOk(obj: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.notOk
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should be equal', args)
return !obj ? this.#t.pass(...me) : this.#t.fail(...me)
}
/**
* Verify that the values are equal
*
* @group Assertion Methods
*/
equal<T extends unknown>(
found: any,
wanted: T,
...[msg, extra]: MessageExtra
): found is T {
this.#t.currentAssert = this.#t.t.equal
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should be equal', args)
if (found === wanted) return this.#t.pass(...me)
if (objects(found, wanted)) {
const { match, diff } = strict(found, wanted, this.#opts)
if (!match) {
Object.assign(me[1], { diff, compare: '===' })
} else {
Object.assign(me[1], {
found,
wanted,
note: 'object identities differ',
compare: '===',
})
}
} else {
Object.assign(me[1], { found, wanted, compare: '===' })
}
return this.#t.fail(...me)
}
/**
* Verify that the values are not equal
*
* @group Assertion Methods
*/
not(found: any, doNotWant: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.not
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not be equal', args)
if (found !== doNotWant) {
return this.#t.pass(...me)
}
Object.assign(me[1], {
found,
doNotWant,
compare: '!==',
})
return this.#t.fail(...me)
}
/**
* Verify that the value is of the type specified
* Type can be either a string, or a constructor.
*
* If a string, then it can match either the `typeof` result
* or 'null' for `null` values, or the `name` property of the
* object's constructor.
*
* @group Assertion Methods
*/
type(
obj: any,
klass: string | Function,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.type
const name =
typeof klass === 'function'
? klass.name || '(anonymous constructor)'
: klass
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(`type is ${name}`, args)
// simplest case, it literally is the same thing
if (obj === klass) {
return this.#t.pass(me[0], me[1])
}
const tof = typeof obj
const type =
!obj && tof === 'object'
? 'null'
: // treat as object, but not Object
// t.type(() => {}, Function)
tof === 'function' &&
typeof klass === 'function' &&
klass !== Object
? 'object'
: tof
if (
(type === 'number' && klass === Number) ||
(type === 'string' && klass === String) ||
(type === 'bigint' && klass === BigInt) ||
(klass === 'array' && Array.isArray(obj)) ||
(type === 'symbol' && klass === Symbol)
) {
return this.#t.pass(...me)
}
if (type === 'object' && klass !== 'object') {
if (typeof klass === 'function') {
me[1].found = Object.getPrototypeOf(obj).constructor.name
me[1].wanted = name
return this.ok(obj instanceof klass, ...me)
}
// check prototype chain for name
// at this point, we already know klass is not a function
// if the klass specified is an obj in the proto chain, pass
// if the name specified is the name of a ctor in the chain, pass
for (let p = obj; p; p = Object.getPrototypeOf(p)) {
const ctor = p.constructor && p.constructor.name
if (p === klass || ctor === name) {
return this.#t.pass(...me)
}
}
}
return this.equal(type, name, ...me)
}
/**
* Verify that the value is loosely equivalent to the supplied pattern
*
* @group Assertion Methods
*/
same(found: any, wanted: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.same
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should be equivalent', args)
const { match, diff } = same(found, wanted, this.#opts)
if (match) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value is not loosely equivalent to the supplied pattern
*
* @group Assertion Methods
*/
notSame(found: any, doNotWant: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.notSame
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not be equivalent', args)
const { match } = same(found, doNotWant, this.#opts)
if (!match) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value is strictly equivalent to the supplied pattern
*
* @group Assertion Methods
*/
strictSame<T extends unknown>(
found: any,
wanted: T,
...[msg, extra]: MessageExtra
): found is T {
this.#t.currentAssert = this.#t.t.strictSame
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'should be equivalent strictly',
args
)
const { match, diff } = strict(found, wanted, this.#opts)
if (match) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value is not strictly equivalent to the supplied
* pattern object
*
* @group Assertion Methods
*/
strictNotSame(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.strictNotSame
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'should not be equivalent strictly',
args
)
const { match } = strict(found, doNotWant, this.#opts)
if (!match) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the object has all of the properties and values in the
* pattern, matching loosely.
*
* @group Assertion Methods
*/
has(found: any, wanted: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.has
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'all provided fields should be equivalent',
args
)
const { match, diff } = has(found, wanted, this.#opts)
if (match) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the object does NOT have all of the properties and values
* in the pattern, matching loosely.
*
* @group Assertion Methods
*/
notHas(found: any, doNotWant: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.notHas
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'all provided fields should not be equivalent',
args
)
const { match } = has(found, doNotWant, this.#opts)
if (!match) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value has all of the properties and values in the
* pattern, matching strictly.
*
* @group Assertion Methods
*/
hasStrict(found: any, wanted: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.hasStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'all provided fields should be equivalent strictly',
args
)
const { match, diff } = hasStrict(found, wanted, this.#opts)
if (match) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value does NOT contain all of the properties and
* values in the test pattern, comparing strictly.
*
* Note that this will pass if the value has *some* of the listed properties,
* or if they do not match the same type.
*
* @group Assertion Methods
*/
notHasStrict(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.notHasStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'all provided fields should not be equivalent strictly',
args
)
const { match } = hasStrict(found, doNotWant, this.#opts)
if (!match) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value matches the pattern provided
*
* @group Assertion Methods
*/
match(found: any, wanted: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.match
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should match pattern', args)
const { match: ok, diff } = match(found, wanted, this.#opts)
if (ok) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value does NOT match the pattern provided.
*
* @group Assertion Methods
*/
notMatch(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.notMatch
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not match pattern', args)
const { match: ok } = match(found, doNotWant, this.#opts)
if (!ok) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value matches the pattern provided, with no
* extra properties.
*
* @group Assertion Methods
*/
matchOnly(found: any, wanted: any, ...[msg, extra]: MessageExtra) {
this.#t.currentAssert = this.#t.t.matchOnly
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should match pattern', args)
const { match: ok, diff } = matchOnly(found, wanted, this.#opts)
if (ok) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value does not match the pattern provided, with no
* extra properties. Ie, it might either not match, or have extra props.
*
* @group Assertion Methods
*/
notMatchOnly(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.notMatchOnly
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not match pattern', args)
const { match: ok } = matchOnly(found, doNotWant, this.#opts)
if (!ok) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value matches the pattern provided, with no
* extra properties.
*
* @group Assertion Methods
*/
matchOnlyStrict(
found: any,
wanted: any,
...[msg, extra]: MessageExtra
) {
// this.#t.currentAssert = this.#t.t.matchOnlyStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should match pattern', args)
const { match: ok, diff } = matchOnlyStrict(
found,
wanted,
this.#opts
)
if (ok) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value does not match the pattern provided, with no
* extra properties. Ie, it might either not match, or have extra props.
*
* @group Assertion Methods
*/
notMatchOnlyStrict(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
// this.#t.currentAssert = this.#t.t.notMatchOnlyStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not match pattern', args)
const { match: ok } = matchOnlyStrict(
found,
doNotWant,
this.#opts
)
if (!ok) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the value matches the pattern provided, but fail if any
* fields *only* match via type coercion.
*
* For example,
*
* ```ts
* t.matchStrict({ a: 1 }, { a: Number }, 'this passes')
* t.matchStrict({ a: 1 }, { a: '1' }, 'this fails')
* ```
*
* @group Assertion Methods
*/
matchStrict(
found: any,
wanted: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.matchStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should match pattern', args)
const { match: ok, diff } = matchStrict(found, wanted, this.#opts)
if (ok) return this.#t.pass(...me)
Object.assign(me[1], { diff })
return this.#t.fail(...me)
}
/**
* Verify that the value does not match the pattern provided, without
* type coercion.
*
* @group Assertion Methods
*/
notMatchStrict(
found: any,
doNotWant: any,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.notMatchStrict
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('should not match pattern', args)
const { match: ok } = matchStrict(found, doNotWant, this.#opts)
if (!ok) return this.#t.pass(...me)
Object.assign(me[1], { found, doNotWant })
return this.#t.fail(...me)
}
/**
* Verify that the object has the wanted property, anywhere in its
* prototype chain.
*
* @group Assertion Methods
*/
hasProp<T extends {}>(
found: T,
wanted: string | number | symbol,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.hasProp
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'specified property should be defined',
args
)
Object.assign(me[1], { found, wanted })
try {
if (
wanted in found &&
(found as { [k: typeof wanted]: any })[wanted] !== undefined
) {
return this.#t.pass(...me)
} else {
return this.#t.fail(...me)
}
} catch (er) {
return this.#t.fail((er as Error)?.message || me[0], me[1])
}
}
/**
* Verify that the object has the wanted property, using
* Object#hasOwnProperty
*
* @group Assertion Methods
*/
hasOwnProp<T extends {}>(
found: T,
wanted: string | number | symbol,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.hasOwnProp
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'specified property should be defined own property',
args
)
Object.assign(me[1], { found, wanted })
try {
if (
hasOwn(found, wanted) &&
(found as { [k: typeof wanted]: any })[wanted] !== undefined
) {
return this.#t.pass(...me)
} else {
return this.#t.fail(...me)
}
} catch (er) {
return this.#t.fail((er as Error)?.message || me[0], me[1])
}
}
/**
* Verify that the object has all of the properties in the `wanted`
* list, anywhere in its prototype chain.
*
* @group Assertion Methods
*/
hasProps<T extends {}>(
found: T,
wanted: Iterable<string | number | symbol>,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.hasProps
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'should have all specified properties',
args
)
Object.assign(me[1], { found, wanted })
if (!isIterable(wanted)) {
return this.#t.fail(
'property list must be iterable object',
me[1]
)
}
for (const prop of wanted) {
if (!['string', 'number', 'symbol'].includes(typeof prop)) {
Object.assign(me[1], { invalidProperty: prop })
return this.#t.fail(
'invalid property in hasProps assertion',
me[1]
)
}
try {
if (
!(
prop in found &&
(found as { [k: typeof prop]: any })[prop] !== undefined
)
) {
return this.#t.fail(...me)
}
} catch (er) {
return this.#t.fail((er as Error)?.message || me[0], me[1])
}
}
return this.#t.pass(...me)
}
/**
* Verify that the object has all of the properties listed in the
* `wanted` list, using Object#hasOwnProperties()
*
* @group Assertion Methods
*/
hasOwnProps<T extends {}>(
found: T,
wanted: Iterable<string | number | symbol>,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.hasOwnProps
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'should have all specified properties',
args
)
Object.assign(me[1], { found, wanted })
if (!isIterable(wanted)) {
return this.#t.fail(
'property list must be iterable object',
me[1]
)
}
for (const prop of wanted) {
if (!['string', 'number', 'symbol'].includes(typeof prop)) {
Object.assign(me[1], { invalidProperty: prop })
return this.#t.fail(
'invalid property in hasOwnProps assertion',
me[1]
)
}
try {
if (
!(
hasOwn(found, prop) &&
(found as { [k: typeof prop]: any })[prop] !== undefined
)
) {
return this.#t.fail(...me)
}
} catch (er) {
return this.#t.fail((er as Error)?.message || me[0], me[1])
}
}
return this.#t.pass(...me)
}
/**
* Verify that the object has all of the properties listed in the
* `wanted` list, using Object#hasOwnProperties(), and no others
*
* @group Assertion Methods
*/
hasOwnPropsOnly<T extends {}>(
found: T,
wanted: Iterable<string | number | symbol>,
...[msg, extra]: MessageExtra
) {
this.#t.currentAssert = this.#t.t.hasOwnPropsOnly
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
'should have all specified properties',
args
)
Object.assign(me[1], { found, wanted })
if (!isIterable(wanted)) {
return this.#t.fail(
'property list must be iterable object',
me[1]
)
}
const seen = new Set<string | symbol | number>()
for (const prop of wanted) {
seen.add(prop)
if (!['string', 'number', 'symbol'].includes(typeof prop)) {
return this.#t.fail(
'invalid property in hasOwnPropsOnly assertion',
{ ...me[1], invalidProperty: prop }
)
}
try {
if (
!(
hasOwn(found, prop) &&
(found as { [k: typeof prop]: any })[prop] !== undefined
)
) {
return this.#t.fail(...me)
}
} catch (er) {
return this.#t.fail((er as Error)?.message || me[0], me[1])
}
}
for (const prop of Object.keys(found)) {
if (!seen.has(prop)) {
return this.#t.fail(me[0], { ...me[1], doNotWant: prop })
}
}
return this.#t.pass(...me)
}
/**
* Verify that the function throws an error.
* Thrown error is tested against the `wanted` param if provided, using
* `t.match()`.
*
* Returns false on failure, or the error object thrown on success
*
* @group Assertion Methods
*/
throws(
fn: Function | (() => any),
...[wanted, msg, extra]: ThrowsArgs
): boolean | Error {
this.#t.currentAssert = this.#t.t.throws
const args = [wanted, msg, extra] as ThrowsArgs
const [w, m, e] = normalizeThrowsArgs(
fn.name || 'expected to throw',
args
)
try {
fn()
return this.#t.fail(m, e)
} catch (err) {
const er = err as Error
if (er?.name) {
Object.defineProperty(er, 'name', {
value: er.name + '',
enumerable: true,
configurable: true,
writable: true,
})
}
return (
(w
? this.match(
isRegExp(wanted) ? er.message : er,
wanted,
m,
e
)
: this.#t.pass(m, e)) && er
)
}
}
/**
* Returns the error object if it throws and that does not fail the test
* (by virtue of being marked skip or todo). Otherwise returns the
* passing status, like other assertions.
*
* @group Assertion Methods
*/
doesNotThrow(
fn: Function | (() => any),
...[msg, extra]: MessageExtra
): boolean | Error {
this.#t.currentAssert = this.#t.t.doesNotThrow
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra(
fn.name || 'expect to not throw',
args
)
try {
fn()
return this.#t.pass(...me)
} catch (er) {
// pull the errorOrigin from the thrown error, if possible
const res =
er !== undefined && er !== null
? this.error(er, ...me)
: this.#t.fail(...me)
return (res && (er as Error)) || res
}
}
/**
* resolves to the error object rejected if it rejects as expected,
* 'false' if it does not, or 'true' if it fails to reject but is marked
* as skip/todo.
*
* @group Assertion Methods
*/
async rejects<T extends any = any>(
fnOrPromise: (() => Promise<T>) | Promise<T>,
...[wanted, msg, extra]: ThrowsArgs
): Promise<boolean | Error> {
const args = [wanted, msg, extra] as ThrowsArgs
const [w, m, e] = normalizeThrowsArgs('expected to reject', args)
this.#t.currentAssert = this.#t.t.rejects
e.at = e.at || stack.at(this.#t.currentAssert)
let p!: Promise<T>
try {
p =
typeof fnOrPromise === 'function'
? fnOrPromise()
: fnOrPromise
} catch (er) {
p = Promise.reject(er)
}
if (!isPromise(p)) {
return this.#t.fail(
'no promise or async function provided to t.rejects',
e
)
}
const d = new Deferred<boolean | Error>()
this.#t.waitOn(d.promise)
try {
await p
d.resolve(this.#t.fail(m, e))
} catch (err) {
const er = err as Error
if (er?.name) {
Object.defineProperty(er, 'name', {
value: er.name + '',
enumerable: true,
configurable: true,
writable: true,
})
}
d.resolve(
(w
? this.match(isRegExp(w) ? er.message : er, w, m, e)
: this.#t.pass(m, e)) &&
(er || true)
)
}
return d.promise
}
/**
* Resolves to 'true' if the promise resolves successfully, 'false' if
* it rejects and fails, or the rejection error if it rejects but the
* failure is accepted by by being marked todo or skip
*
* @group Assertion Methods
*/
async resolves<T extends any = any>(
fnOrPromise: Promise<T> | (() => Promise<T>),
...[msg, extra]: MessageExtra
): Promise<boolean | Error> {
this.#t.currentAssert = this.#t.t.resolves
const args = [msg, extra] as MessageExtra
const me = normalizeMessageExtra('expected to resolve', args)
me[1].at = me[1].at || stack.at(this.#t.currentAssert)
let p!: Promise<T>
try {
p =
typeof fnOrPromise === 'function'
? fnOrPromise()
: fnOrPromise
} catch (er) {
p = Promise.reject(er)
}
if (!isPromise(p)) {
return this.#t.fail(
'no promise or async function provided to t.resolves',
me[1]
)
}
const d = new Deferred<boolean | Error>()
this.#t.waitOn(d.promise)
try {
await p
d.resolve(this.#t.pass(...me))
} catch (er) {
// pull the errorOrigin from the thrown error, if possible
const res =
er !== undefined && er !== null
? this.error(er, ...me)
: this.#t.fail(...me)
d.resolve((res && (er as Error)) || res)
}
return d.promise
}
/**
* Test the resolved promise result with `t.match()`
*
* Resolves to true if it passes, false if the promise rejects or the match
* fails, or the rejection error value if the promise rejects but the
* assertion passes by being marked todo/skip.
*
* @group Assertion Methods
*/
async resolveMatch<T extends any = any>(
fnOrPromise: Promise<T> | (() => Promise<T>),
wanted: any,