summaryrefslogtreecommitdiff
path: root/tst/either.test.ts
blob: 6f375089296f1eef578021711834f9a98cee3c34 (plain) (blame)
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
import { Either } from '../lib/index';

describe('Either.basic', () => {
    test('mapRight/mapLeft/swap', () => {
        const r = Either.right<string, number>(2)
            .mapRight((n) => n + 1)
            .mapLeft((e) => e.toUpperCase());

        expect(r.right().get()).toBe(3);
        expect(r.swap().left().get()).toBe(3);

        const l = Either.left<string, number>('nope').mapRight((n) => n + 1);
        expect(l.left().get()).toBe('nope');
        expect(l.swap().right().get()).toBe('nope');
    });

    test('joinRight combines rights', () => {
        const a = Either.right<string, number>(2);
        const b = Either.right<string, number>(3);
        const res = a.joinRight(b, (x, y) => x + y);
        expect(res.right().get()).toBe(5);
    });
});

describe('Either.retrying', () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });

    test('succeeds on first attempt', async () => {
        const supplier = jest.fn().mockResolvedValue(Either.right<string, string>('success'));
        const interval = jest.fn().mockResolvedValue(undefined);

        const result = await Either.retrying(supplier, 3, interval);

        expect(result.right().get()).toBe('success');
        expect(supplier).toHaveBeenCalledTimes(1);
    });

    test('never succeeds after all attempts', async () => {
        const supplier = jest.fn().mockResolvedValue(Either.left<string, string>('failed'));
        const interval = jest.fn().mockResolvedValue(undefined);

        const result = await Either.retrying(supplier, 3, interval);

        expect(result.left().get()).toBe('failed');
        expect(supplier).toHaveBeenCalledTimes(3);
    });

    test('attempts correct number of times and calls interval with backoff', async () => {
        const supplier = jest
            .fn()
            .mockResolvedValueOnce(Either.left<string, string>('attempt 1 failed'))
            .mockResolvedValueOnce(Either.left<string, string>('attempt 2 failed'))
            .mockResolvedValueOnce(Either.right<string, string>('attempt 3 success'));

        const interval = jest.fn().mockResolvedValue(undefined);

        const result = await Either.retrying(supplier, 3, interval);

        expect(result.right().get()).toBe('attempt 3 success');
        expect(supplier).toHaveBeenCalledTimes(3);
        expect(interval).toHaveBeenCalledTimes(3);
        expect(interval).toHaveBeenNthCalledWith(1, 0);
        expect(interval).toHaveBeenNthCalledWith(2, 1);
        expect(interval).toHaveBeenNthCalledWith(3, 2);
    });
});