summaryrefslogtreecommitdiff
path: root/tst/argv.test.ts
blob: 1eae0598cc48f043210a6c185582385d2d8ce47e (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
import { argv, getArg, isArgKey } from '../lib/index';

describe('process/argv', () => {
    test('isArgKey detects keys', () => {
        expect(isArgKey('--foo')).toBe(true);
        expect(isArgKey('foo')).toBe(false);
        expect(isArgKey('-f')).toBe(false);
    });

    test('getArg returns absent default when missing', () => {
        const res = getArg('--foo', ['--bar', 'x'], { absent: 'nope', present: (v: string) => v });
        expect(res.right().get()).toBe('nope');
    });

    test('getArg errors when missing and no absent default', () => {
        const res = getArg('--foo', ['--bar', 'x'], { present: (v: string) => v });
        expect(res.left().get().message).toMatch(/arg --foo is not present/);
    });

    test('getArg reads value from equals form', () => {
        const res = getArg('--foo', ['--foo=bar'], { present: (v: string) => v });
        expect(res.right().get()).toBe('bar');
    });

    test('getArg reads value from next token form', () => {
        const res = getArg('--foo', ['--foo', 'bar'], { present: (v: string) => v });
        expect(res.right().get()).toBe('bar');
    });

    test('getArg uses unspecified when value missing', () => {
        const res = getArg('--foo', ['--foo', '--bar', 'x'], {
            unspecified: 'default',
            present: (v: string) => v,
        });
        expect(res.right().get()).toBe('default');
    });

    test('argv maps multiple args with handlers', () => {
        const res = argv(
            ['--port', '--host'] as const,
            {
                '--port': {
                    present: (v: string) => parseInt(v, 10),
                },
                '--host': {
                    absent: '127.0.0.1',
                    present: (v: string) => v,
                },
            },
            ['--port', '8080'],
        );

        expect(res.right().get()).toEqual({ '--port': 8080, '--host': '127.0.0.1' });
    });
});