-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathindex.test.ts
More file actions
1395 lines (1037 loc) · 41.4 KB
/
Copy pathindex.test.ts
File metadata and controls
1395 lines (1037 loc) · 41.4 KB
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 * as td from 'testdouble'
import {
err,
Err,
errAsync,
fromAsyncThrowable,
fromPromise,
fromSafePromise,
fromThrowable,
ok,
Ok,
okAsync,
Result,
ResultAsync,
} from '../src'
import { describe, expect, it, vitest } from 'vitest'
describe('Result.Ok', () => {
it('Creates an Ok value', () => {
const okVal = ok(12)
expect(okVal.isOk()).toBe(true)
expect(okVal.isErr()).toBe(false)
expect(okVal).toBeInstanceOf(Ok)
})
it('Creates an Ok value with null', () => {
const okVal = ok(null)
expect(okVal.isOk()).toBe(true)
expect(okVal.isErr()).toBe(false)
expect(okVal._unsafeUnwrap()).toBe(null)
})
it('Creates an Ok value with undefined', () => {
const okVal = ok(undefined)
expect(okVal.isOk()).toBe(true)
expect(okVal.isErr()).toBe(false)
expect(okVal._unsafeUnwrap()).toBeUndefined()
})
it('Is comparable', () => {
expect(ok(42)).toEqual(ok(42))
expect(ok(42)).not.toEqual(ok(43))
})
it('Maps over an Ok value', () => {
const okVal = ok(12)
const mapFn = vitest.fn((number) => number.toString())
const mapped = okVal.map(mapFn)
expect(mapped.isOk()).toBe(true)
expect(mapped._unsafeUnwrap()).toBe('12')
expect(mapFn).toHaveBeenCalledTimes(1)
})
it('Skips `mapErr`', () => {
const mapErrorFunc = vitest.fn((_error) => 'mapped error value')
const notMapped = ok(12).mapErr(mapErrorFunc)
expect(notMapped.isOk()).toBe(true)
expect(mapErrorFunc).not.toHaveBeenCalledTimes(1)
})
describe('andThen', () => {
it('Maps to an Ok', () => {
const okVal = ok(12)
const flattened = okVal.andThen((_number) => {
// ...
// complex logic
// ...
return ok({ data: 'why not' })
})
expect(flattened.isOk()).toBe(true)
expect(flattened._unsafeUnwrap()).toStrictEqual({ data: 'why not' })
})
it('Maps to an Err', () => {
const okval = ok(12)
const flattened = okval.andThen((_number) => {
// ...
// complex logic
// ...
return err('Whoopsies!')
})
expect(flattened.isOk()).toBe(false)
const nextFn = vitest.fn((_val) => ok('noop'))
flattened.andThen(nextFn)
expect(nextFn).not.toHaveBeenCalled()
})
})
describe('andThrough', () => {
it('Calls the passed function but returns an original ok', () => {
const okVal = ok(12)
const passedFn = vitest.fn((_number) => ok(undefined))
const thrued = okVal.andThrough(passedFn)
expect(thrued.isOk()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(thrued._unsafeUnwrap()).toStrictEqual(12)
})
it('Maps to an Err', () => {
const okval = ok(12)
const thrued = okval.andThen((_number) => {
// ...
// complex logic
// ...
return err('Whoopsies!')
})
expect(thrued.isOk()).toBe(false)
expect(thrued._unsafeUnwrapErr()).toStrictEqual('Whoopsies!')
const nextFn = vitest.fn((_val) => ok('noop'))
thrued.andThen(nextFn)
expect(nextFn).not.toHaveBeenCalled()
})
})
describe('andTee', () => {
it('Calls the passed function but returns an original ok', () => {
const okVal = ok(12)
const passedFn = vitest.fn((_number) => {})
const teed = okVal.andTee(passedFn)
expect(teed.isOk()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(teed._unsafeUnwrap()).toStrictEqual(12)
})
it('returns an original ok even when the passed function fails', () => {
const okVal = ok(12)
const passedFn = vitest.fn((_number) => {
throw new Error('OMG!')
})
const teed = okVal.andTee(passedFn)
expect(teed.isOk()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(teed._unsafeUnwrap()).toStrictEqual(12)
})
})
describe('orTee', () => {
it('Calls the passed function but returns an original err', () => {
const errVal = err(12)
const passedFn = vitest.fn((_number) => {})
const teed = errVal.orTee(passedFn)
expect(teed.isErr()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(teed._unsafeUnwrapErr()).toStrictEqual(12)
})
it('returns an original err even when the passed function fails', () => {
const errVal = err(12)
const passedFn = vitest.fn((_number) => {
throw new Error('OMG!')
})
const teed = errVal.orTee(passedFn)
expect(teed.isErr()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(teed._unsafeUnwrapErr()).toStrictEqual(12)
})
})
describe('andFinally', () => {
it('calls the callback and returns the original ok value', () => {
const okVal = ok("original ok value");
const andFinallyFn = jest.fn(() => ok("finally ok value"));
const finalResult = okVal.andFinally(andFinallyFn);
expect(andFinallyFn).toHaveBeenCalledTimes(1);
expect(finalResult._unsafeUnwrap()).toBe("original ok value");
})
it('calls the callback and returns the error from the callback', () => {
const okVal = ok("original ok value");
const andFinallyFn = jest.fn(() => err("error from callback"));
const finalResult = okVal.andFinally(andFinallyFn);
expect(andFinallyFn).toHaveBeenCalledTimes(1);
expect(finalResult._unsafeUnwrapErr()).toBe("error from callback");
})
})
describe('asyncAndThrough', () => {
it('Calls the passed function but returns an original ok as Async', async () => {
const okVal = ok(12)
const passedFn = vitest.fn((_number) => okAsync(undefined))
const teedAsync = okVal.asyncAndThrough(passedFn)
expect(teedAsync).toBeInstanceOf(ResultAsync)
const teed = await teedAsync
expect(teed.isOk()).toBe(true)
expect(passedFn).toHaveBeenCalledTimes(1)
expect(teed._unsafeUnwrap()).toStrictEqual(12)
})
it('Maps to an Err', async () => {
const okval = ok(12)
const teedAsync = okval.asyncAndThen((_number) => {
// ...
// complex logic
// ...
return errAsync('Whoopsies!')
})
expect(teedAsync).toBeInstanceOf(ResultAsync)
const teed = await teedAsync
expect(teed.isOk()).toBe(false)
expect(teed._unsafeUnwrapErr()).toStrictEqual('Whoopsies!')
const nextFn = vitest.fn((_val) => ok('noop'))
teed.andThen(nextFn)
expect(nextFn).not.toHaveBeenCalled()
})
})
describe('orElse', () => {
it('Skips orElse on an Ok value', () => {
const okVal = ok(12)
const errorCallback = vitest.fn((_errVal) => err<number, string>('It is now a string'))
expect(okVal.orElse(errorCallback)).toEqual(ok(12))
expect(errorCallback).not.toHaveBeenCalled()
})
})
it('unwrapOr and return the Ok value', () => {
const okVal = ok(12)
expect(okVal.unwrapOr(1)).toEqual(12)
})
it('Maps to a ResultAsync', async () => {
const okVal = ok(12)
const flattened = okVal.asyncAndThen((_number) => {
// ...
// complex async logic
// ...
return okAsync({ data: 'why not' })
})
expect(flattened).toBeInstanceOf(ResultAsync)
const newResult = await flattened
expect(newResult.isOk()).toBe(true)
expect(newResult._unsafeUnwrap()).toStrictEqual({ data: 'why not' })
})
it('Maps to a promise', async () => {
const asyncMapper = vitest.fn((_val) => {
// ...
// complex logic
// ..
// db queries
// network calls
// disk io
// etc ...
return Promise.resolve('Very Nice!')
})
const okVal = ok(12)
const promise = okVal.asyncMap(asyncMapper)
expect(promise).toBeInstanceOf(ResultAsync)
const newResult = await promise
expect(newResult.isOk()).toBe(true)
expect(asyncMapper).toHaveBeenCalledTimes(1)
expect(newResult._unsafeUnwrap()).toStrictEqual('Very Nice!')
})
it('Matches on an Ok', () => {
const okMapper = vitest.fn((_val) => 'weeeeee')
const errMapper = vitest.fn((_val) => 'wooooo')
const matched = ok(12).match(okMapper, errMapper)
expect(matched).toBe('weeeeee')
expect(okMapper).toHaveBeenCalledTimes(1)
expect(errMapper).not.toHaveBeenCalled()
})
it('Unwraps without issue', () => {
const okVal = ok(12)
expect(okVal._unsafeUnwrap()).toBe(12)
})
it('Can read the value after narrowing', () => {
const fallible: () => Result<string, number> = () => ok('safe to read')
const val = fallible()
// After this check we val is narrowed to Ok<string, number>. Without this
// line TypeScript will not allow accessing val.value.
if (val.isErr()) return
expect(val.value).toBe('safe to read')
})
})
describe('Result.Err', () => {
it('Creates an Err value', () => {
const errVal = err('I have you now.')
expect(errVal.isOk()).toBe(false)
expect(errVal.isErr()).toBe(true)
expect(errVal).toBeInstanceOf(Err)
})
it('Is comparable', () => {
expect(err(42)).toEqual(err(42))
expect(err(42)).not.toEqual(err(43))
})
it('Skips `map`', () => {
const errVal = err('I am your father')
const mapper = vitest.fn((_value) => 'noooo')
const hopefullyNotMapped = errVal.map(mapper)
expect(hopefullyNotMapped.isErr()).toBe(true)
expect(mapper).not.toHaveBeenCalled()
expect(hopefullyNotMapped._unsafeUnwrapErr()).toEqual(errVal._unsafeUnwrapErr())
})
it('Maps over an Err', () => {
const errVal = err('Round 1, Fight!')
const mapper = vitest.fn((error: string) => error.replace('1', '2'))
const mapped = errVal.mapErr(mapper)
expect(mapped.isErr()).toBe(true)
expect(mapper).toHaveBeenCalledTimes(1)
expect(mapped._unsafeUnwrapErr()).not.toEqual(errVal._unsafeUnwrapErr())
})
it('unwrapOr and return the default value', () => {
const okVal = err<number, string>('Oh nooo')
expect(okVal.unwrapOr(1)).toEqual(1)
})
it('Skips over andThen', () => {
const errVal = err('Yolo')
const mapper = vitest.fn((_val) => ok<string, string>('yooyo'))
const hopefullyNotFlattened = errVal.andThen(mapper)
expect(hopefullyNotFlattened.isErr()).toBe(true)
expect(mapper).not.toHaveBeenCalled()
expect(errVal._unsafeUnwrapErr()).toEqual('Yolo')
})
it('Skips over andThrough', () => {
const errVal = err('Yolo')
const mapper = vitest.fn((_val) => ok<void, string>(undefined))
const hopefullyNotFlattened = errVal.andThrough(mapper)
expect(hopefullyNotFlattened.isErr()).toBe(true)
expect(mapper).not.toHaveBeenCalled()
expect(errVal._unsafeUnwrapErr()).toEqual('Yolo')
})
it('Skips over andTee', () => {
const errVal = err('Yolo')
const mapper = vitest.fn((_val) => {})
const hopefullyNotFlattened = errVal.andTee(mapper)
expect(hopefullyNotFlattened.isErr()).toBe(true)
expect(mapper).not.toHaveBeenCalled()
expect(errVal._unsafeUnwrapErr()).toEqual('Yolo')
})
describe('andFinally', () => {
it('calls the callback and returns the original error', () => {
const okVal = err("original error");
const andFinallyFn = jest.fn(() => ok("finally ok value"));
const finalResult = okVal.andFinally(andFinallyFn);
expect(andFinallyFn).toHaveBeenCalledTimes(1);
expect(finalResult._unsafeUnwrapErr()).toBe("original error");
})
it('calls the callback and returns the error from the callback', () => {
const okVal = err("original error");
const andFinallyFn = jest.fn(() => err("error from callback"));
const finalResult = okVal.andFinally(andFinallyFn);
expect(andFinallyFn).toHaveBeenCalledTimes(1);
expect(finalResult._unsafeUnwrapErr()).toBe("error from callback");
})
})
it('Skips over asyncAndThrough but returns ResultAsync instead', async () => {
const errVal = err('Yolo')
const mapper = vitest.fn((_val) => okAsync<string, unknown>('Async'))
const hopefullyNotFlattened = errVal.asyncAndThrough(mapper)
expect(hopefullyNotFlattened).toBeInstanceOf(ResultAsync)
const result = await hopefullyNotFlattened
expect(result.isErr()).toBe(true)
expect(mapper).not.toHaveBeenCalled()
expect(result._unsafeUnwrapErr()).toEqual('Yolo')
})
it('Transforms error into ResultAsync within `asyncAndThen`', async () => {
const errVal = err('Yolo')
const asyncMapper = vitest.fn((_val) => okAsync<string, string>('yooyo'))
const hopefullyNotFlattened = errVal.asyncAndThen(asyncMapper)
expect(hopefullyNotFlattened).toBeInstanceOf(ResultAsync)
expect(asyncMapper).not.toHaveBeenCalled()
const syncResult = await hopefullyNotFlattened
expect(syncResult._unsafeUnwrapErr()).toEqual('Yolo')
})
it('Does not invoke callback within `asyncMap`', async () => {
const asyncMapper = vitest.fn((_val) => {
// ...
// complex logic
// ..
// db queries
// network calls
// disk io
// etc ...
return Promise.resolve('Very Nice!')
})
const errVal = err('nooooooo')
const promise = errVal.asyncMap(asyncMapper)
expect(promise).toBeInstanceOf(ResultAsync)
const sameResult = await promise
expect(sameResult.isErr()).toBe(true)
expect(asyncMapper).not.toHaveBeenCalled()
expect(sameResult._unsafeUnwrapErr()).toEqual(errVal._unsafeUnwrapErr())
})
it('Matches on an Err', () => {
const okMapper = vitest.fn((_val) => 'weeeeee')
const errMapper = vitest.fn((_val) => 'wooooo')
const matched = err(12).match(okMapper, errMapper)
expect(matched).toBe('wooooo')
expect(okMapper).not.toHaveBeenCalled()
expect(errMapper).toHaveBeenCalledTimes(1)
})
it('Throws when you unwrap an Err', () => {
const errVal = err('woopsies')
expect(() => {
errVal._unsafeUnwrap()
}).toThrowError()
})
it('Unwraps without issue', () => {
const okVal = err(12)
expect(okVal._unsafeUnwrapErr()).toBe(12)
})
describe('orElse', () => {
it('invokes the orElse callback on an Err value', () => {
const okVal = err('BOOOM!')
const errorCallback = vitest.fn((_errVal) => err(true))
expect(okVal.orElse(errorCallback)).toEqual(err(true))
expect(errorCallback).toHaveBeenCalledTimes(1)
})
})
})
describe('Result.fromThrowable', () => {
it('Creates a function that returns an OK result when the inner function does not throw', () => {
const hello = (): string => 'hello'
const safeHello = Result.fromThrowable(hello)
const result = hello()
const safeResult = safeHello()
expect(safeResult).toBeInstanceOf(Ok)
expect(result).toEqual(safeResult._unsafeUnwrap())
})
// Added for issue #300 -- the test here is not so much that expectations are met as that the test compiles.
it('Accepts an inner function which takes arguments', () => {
const hello = (fname: string): string => `hello, ${fname}`
const safeHello = Result.fromThrowable(hello)
const result = hello('Dikembe')
const safeResult = safeHello('Dikembe')
expect(safeResult).toBeInstanceOf(Ok)
expect(result).toEqual(safeResult._unsafeUnwrap())
})
it('Creates a function that returns an err when the inner function throws', () => {
const thrower = (): string => {
throw new Error()
}
// type: () => Result<string, unknown>
// received types from thrower fn, no errorFn is provides therefore Err type is unknown
const safeThrower = Result.fromThrowable(thrower)
const result = safeThrower()
expect(result).toBeInstanceOf(Err)
expect(result._unsafeUnwrapErr()).toBeInstanceOf(Error)
})
it('Accepts an error handler as a second argument', () => {
const thrower = (): string => {
throw new Error()
}
type MessageObject = { message: string }
const toMessageObject = (): MessageObject => ({ message: 'error' })
// type: () => Result<string, MessageObject>
// received types from thrower fn and errorFn return type
const safeThrower = Result.fromThrowable(thrower, toMessageObject)
const result = safeThrower()
expect(result.isOk()).toBe(false)
expect(result.isErr()).toBe(true)
expect(result).toBeInstanceOf(Err)
expect(result._unsafeUnwrapErr()).toEqual({ message: 'error' })
})
it('has a top level export', () => {
expect(fromThrowable).toBe(Result.fromThrowable)
})
})
describe('Utils', () => {
describe('`Result.combine`', () => {
describe('Synchronous `combine`', () => {
it('Combines a list of results into an Ok value', () => {
const resultList = [ok(123), ok(456), ok(789)]
const result = Result.combine(resultList)
expect(result.isOk()).toBe(true)
expect(result._unsafeUnwrap()).toEqual([123, 456, 789])
})
it('Combines a list of results into an Err value', () => {
const resultList: Result<number, string>[] = [
ok(123),
err('boooom!'),
ok(456),
err('ahhhhh!'),
]
const result = Result.combine(resultList)
expect(result.isErr()).toBe(true)
expect(result._unsafeUnwrapErr()).toBe('boooom!')
})
it('Combines heterogeneous lists', () => {
type HeterogenousList = [
Result<string, string>,
Result<number, number>,
Result<boolean, boolean>,
]
const heterogenousList: HeterogenousList = [ok('Yooooo'), ok(123), ok(true)]
type ExpecteResult = Result<[string, number, boolean], string | number | boolean>
const result: ExpecteResult = Result.combine(heterogenousList)
expect(result._unsafeUnwrap()).toEqual(['Yooooo', 123, true])
})
it('Does not destructure / concatenate arrays', () => {
type HomogenousList = [Result<string[], boolean>, Result<number[], string>]
const homogenousList: HomogenousList = [ok(['hello', 'world']), ok([1, 2, 3])]
type ExpectedResult = Result<[string[], number[]], boolean | string>
const result: ExpectedResult = Result.combine(homogenousList)
expect(result._unsafeUnwrap()).toEqual([
['hello', 'world'],
[1, 2, 3],
])
})
})
describe('`ResultAsync.combine`', () => {
it('Combines a list of async results into an Ok value', async () => {
const asyncResultList = [okAsync(123), okAsync(456), okAsync(789)]
const resultAsync: ResultAsync<number[], never[]> = ResultAsync.combine(asyncResultList)
expect(resultAsync).toBeInstanceOf(ResultAsync)
const result = await ResultAsync.combine(asyncResultList)
expect(result.isOk()).toBe(true)
expect(result._unsafeUnwrap()).toEqual([123, 456, 789])
})
it('Combines a list of results into an Err value', async () => {
const resultList: ResultAsync<number, string>[] = [
okAsync(123),
errAsync('boooom!'),
okAsync(456),
errAsync('ahhhhh!'),
]
const result = await ResultAsync.combine(resultList)
expect(result.isErr()).toBe(true)
expect(result._unsafeUnwrapErr()).toBe('boooom!')
})
it('Combines heterogeneous lists', async () => {
type HeterogenousList = [
ResultAsync<string, string>,
ResultAsync<number, number>,
ResultAsync<boolean, boolean>,
ResultAsync<number[], string>,
]
const heterogenousList: HeterogenousList = [
okAsync('Yooooo'),
okAsync(123),
okAsync(true),
okAsync([1, 2, 3]),
]
type ExpecteResult = Result<[string, number, boolean, number[]], string | number | boolean>
const result: ExpecteResult = await ResultAsync.combine(heterogenousList)
expect(result._unsafeUnwrap()).toEqual(['Yooooo', 123, true, [1, 2, 3]])
})
})
})
describe('`Result.combineWithAllErrors`', () => {
describe('Synchronous `combineWithAllErrors`', () => {
it('Combines a list of results into an Ok value', () => {
const resultList = [ok(123), ok(456), ok(789)]
const result = Result.combineWithAllErrors(resultList)
expect(result.isOk()).toBe(true)
expect(result._unsafeUnwrap()).toEqual([123, 456, 789])
})
it('Combines a list of results into an Err value', () => {
const resultList: Result<number, string>[] = [
ok(123),
err('boooom!'),
ok(456),
err('ahhhhh!'),
]
const result = Result.combineWithAllErrors(resultList)
expect(result.isErr()).toBe(true)
expect(result._unsafeUnwrapErr()).toEqual(['boooom!', 'ahhhhh!'])
})
it('Combines heterogeneous lists', () => {
type HeterogenousList = [
Result<string, string>,
Result<number, number>,
Result<boolean, boolean>,
]
const heterogenousList: HeterogenousList = [ok('Yooooo'), ok(123), ok(true)]
type ExpecteResult = Result<[string, number, boolean], (string | number | boolean)[]>
const result: ExpecteResult = Result.combineWithAllErrors(heterogenousList)
expect(result._unsafeUnwrap()).toEqual(['Yooooo', 123, true])
})
it('Does not destructure / concatenate arrays', () => {
type HomogenousList = [Result<string[], boolean>, Result<number[], string>]
const homogenousList: HomogenousList = [ok(['hello', 'world']), ok([1, 2, 3])]
type ExpectedResult = Result<[string[], number[]], (boolean | string)[]>
const result: ExpectedResult = Result.combineWithAllErrors(homogenousList)
expect(result._unsafeUnwrap()).toEqual([
['hello', 'world'],
[1, 2, 3],
])
})
})
describe('`ResultAsync.combineWithAllErrors`', () => {
it('Combines a list of async results into an Ok value', async () => {
const asyncResultList = [okAsync(123), okAsync(456), okAsync(789)]
const result = await ResultAsync.combineWithAllErrors(asyncResultList)
expect(result.isOk()).toBe(true)
expect(result._unsafeUnwrap()).toEqual([123, 456, 789])
})
it('Combines a list of results into an Err value', async () => {
const asyncResultList: ResultAsync<number, string>[] = [
okAsync(123),
errAsync('boooom!'),
okAsync(456),
errAsync('ahhhhh!'),
]
const result = await ResultAsync.combineWithAllErrors(asyncResultList)
expect(result.isErr()).toBe(true)
expect(result._unsafeUnwrapErr()).toEqual(['boooom!', 'ahhhhh!'])
})
it('Combines heterogeneous lists', async () => {
type HeterogenousList = [
ResultAsync<string, string>,
ResultAsync<number, number>,
ResultAsync<boolean, boolean>,
]
const heterogenousList: HeterogenousList = [okAsync('Yooooo'), okAsync(123), okAsync(true)]
type ExpecteResult = Result<[string, number, boolean], (string | number | boolean)[]>
const result: ExpecteResult = await ResultAsync.combineWithAllErrors(heterogenousList)
expect(result._unsafeUnwrap()).toEqual(['Yooooo', 123, true])
})
})
describe('testdouble `ResultAsync.combine`', () => {
interface ITestInterface {
getName(): string
setName(name: string): void
getAsyncResult(): ResultAsync<ITestInterface, Error>
}
it('Combines `testdouble` proxies from mocks generated via interfaces', async () => {
const mock = td.object<ITestInterface>()
const result = await ResultAsync.combine([okAsync(mock)] as const)
expect(result).toBeDefined()
expect(result.isErr()).toBeFalsy()
const unwrappedResult = result._unsafeUnwrap()
expect(unwrappedResult.length).toBe(1)
expect(unwrappedResult[0]).toBe(mock)
})
})
})
})
describe('ResultAsync', () => {
it('Is awaitable to a Result', async () => {
// For a success value
const asyncVal = okAsync(12)
expect(asyncVal).toBeInstanceOf(ResultAsync)
const val = await asyncVal
expect(val).toBeInstanceOf(Ok)
expect(val._unsafeUnwrap()).toEqual(12)
// For an error
const asyncErr = errAsync('Wrong format')
expect(asyncErr).toBeInstanceOf(ResultAsync)
const err = await asyncErr
expect(err).toBeInstanceOf(Err)
expect(err._unsafeUnwrapErr()).toEqual('Wrong format')
})
describe('acting as a Promise<Result>', () => {
it('Is chainable like any Promise', async () => {
// For a success value
const asyncValChained = okAsync(12).then((res) => {
if (res.isOk()) {
return res.value + 2
}
})
expect(asyncValChained).toBeInstanceOf(Promise)
const val = await asyncValChained
expect(val).toEqual(14)
// For an error
const asyncErrChained = errAsync('Oops').then((res) => {
if (res.isErr()) {
return res.error + '!'
}
})
expect(asyncErrChained).toBeInstanceOf(Promise)
const err = await asyncErrChained
expect(err).toEqual('Oops!')
})
it('Can be used with Promise.all', async () => {
const allResult = await Promise.all([okAsync<string, Error>('1')])
expect(allResult).toHaveLength(1)
expect(allResult[0]).toBeInstanceOf(Ok)
if (!(allResult[0] instanceof Ok)) return
expect(allResult[0].isOk()).toBe(true)
expect(allResult[0]._unsafeUnwrap()).toEqual('1')
})
it('rejects if the underlying promise is rejected', () => {
const asyncResult = new ResultAsync(Promise.reject('oops'))
expect(asyncResult).rejects.toBe('oops')
})
})
describe('map', () => {
it('Maps a value using a synchronous function', async () => {
const asyncVal = okAsync(12)
const mapSyncFn = vitest.fn((number) => number.toString())
const mapped = asyncVal.map(mapSyncFn)
expect(mapped).toBeInstanceOf(ResultAsync)
const newVal = await mapped
expect(newVal.isOk()).toBe(true)
expect(newVal._unsafeUnwrap()).toBe('12')
expect(mapSyncFn).toHaveBeenCalledTimes(1)
})
it('Maps a value using an asynchronous function', async () => {
const asyncVal = okAsync(12)
const mapAsyncFn = vitest.fn((number) => Promise.resolve(number.toString()))
const mapped = asyncVal.map(mapAsyncFn)
expect(mapped).toBeInstanceOf(ResultAsync)
const newVal = await mapped
expect(newVal.isOk()).toBe(true)
expect(newVal._unsafeUnwrap()).toBe('12')
expect(mapAsyncFn).toHaveBeenCalledTimes(1)
})
it('Skips an error', async () => {
const asyncErr = errAsync<number, string>('Wrong format')
const mapSyncFn = vitest.fn((number) => number.toString())
const notMapped = asyncErr.map(mapSyncFn)
expect(notMapped).toBeInstanceOf(ResultAsync)
const newVal = await notMapped
expect(newVal.isErr()).toBe(true)
expect(newVal._unsafeUnwrapErr()).toBe('Wrong format')
expect(mapSyncFn).toHaveBeenCalledTimes(0)
})
})
describe('mapErr', () => {
it('Maps an error using a synchronous function', async () => {
const asyncErr = errAsync('Wrong format')
const mapErrSyncFn = vitest.fn((str) => 'Error: ' + str)
const mappedErr = asyncErr.mapErr(mapErrSyncFn)
expect(mappedErr).toBeInstanceOf(ResultAsync)
const newVal = await mappedErr
expect(newVal.isErr()).toBe(true)
expect(newVal._unsafeUnwrapErr()).toBe('Error: Wrong format')
expect(mapErrSyncFn).toHaveBeenCalledTimes(1)
})
it('Maps an error using an asynchronous function', async () => {
const asyncErr = errAsync('Wrong format')
const mapErrAsyncFn = vitest.fn((str) => Promise.resolve('Error: ' + str))
const mappedErr = asyncErr.mapErr(mapErrAsyncFn)
expect(mappedErr).toBeInstanceOf(ResultAsync)
const newVal = await mappedErr
expect(newVal.isErr()).toBe(true)
expect(newVal._unsafeUnwrapErr()).toBe('Error: Wrong format')
expect(mapErrAsyncFn).toHaveBeenCalledTimes(1)
})
it('Skips a value', async () => {
const asyncVal = okAsync(12)
const mapErrSyncFn = vitest.fn((str) => 'Error: ' + str)
const notMapped = asyncVal.mapErr(mapErrSyncFn)
expect(notMapped).toBeInstanceOf(ResultAsync)
const newVal = await notMapped
expect(newVal.isOk()).toBe(true)
expect(newVal._unsafeUnwrap()).toBe(12)
expect(mapErrSyncFn).toHaveBeenCalledTimes(0)
})
})
describe('andThen', () => {
it('Maps a value using a function returning a ResultAsync', async () => {
const asyncVal = okAsync(12)
const andThenResultAsyncFn = vitest.fn(() => okAsync('good'))
const mapped = asyncVal.andThen(andThenResultAsyncFn)
expect(mapped).toBeInstanceOf(ResultAsync)
const newVal = await mapped
expect(newVal.isOk()).toBe(true)
expect(newVal._unsafeUnwrap()).toBe('good')
expect(andThenResultAsyncFn).toHaveBeenCalledTimes(1)
})
it('Maps a value using a function returning a Result', async () => {
const asyncVal = okAsync(12)
const andThenResultFn = vitest.fn(() => ok('good'))
const mapped = asyncVal.andThen(andThenResultFn)
expect(mapped).toBeInstanceOf(ResultAsync)
const newVal = await mapped
expect(newVal.isOk()).toBe(true)
expect(newVal._unsafeUnwrap()).toBe('good')
expect(andThenResultFn).toHaveBeenCalledTimes(1)
})