๐Ÿ“ฆ ljharb / pargs

๐Ÿ“„ isParseArgsError.mjs ยท 78 lines
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
78import test from 'tape';
import v from 'es-value-fixtures';
import inspect from 'object-inspect';
import { parseArgs } from 'util';

import isParseArgsError from '../isParseArgsError.mjs';

test('isParseArgsError', (t) => {
	t.equal(typeof isParseArgsError, 'function', 'is a function');

	(/** @type {(typeof v.primitives)[number] | function} */ [].concat(
		// @ts-expect-error TS sucks with concat
		v.primitives,
		() => {},
	)).forEach((x) => {
		t.equal(isParseArgsError(x), false, `${inspect(x)} is not an object`);
	});

	t.equal(isParseArgsError({}), false, 'object must be an Error');

	const err = new Error();
	t.equal(isParseArgsError(err), false, 'error must have a `code` property');

	try {
		parseArgs({
			args: ['--bar'],
			options: { foo: { type: 'boolean' } },
		});
		t.fail();
	} catch (e) {
		// @ts-expect-error
		t.equal(e.code, 'ERR_PARSE_ARGS_UNKNOWN_OPTION');
		t.equal(isParseArgsError(e), true, 'unknown option');
	}

	try {
		parseArgs({
			args: ['--foo=bar'],
			options: { foo: { type: 'boolean' } },
		});
		t.fail();
	} catch (e) {
		// @ts-expect-error
		t.equal(e.code, 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE');
		t.equal(isParseArgsError(e), true, 'invalid option value');
	}

	try {
		// @ts-expect-error
		parseArgs({ args: true });
		t.fail();
	} catch (e) {
		// @ts-expect-error
		t.equal(e.code, 'ERR_INVALID_ARG_TYPE');
		t.equal(isParseArgsError(e), true, 'invalid argument config type');
	}

	try {
		parseArgs(({ args: [], options: { foo: { type: 'boolean', short: 'fo' } } }));
		t.fail();
	} catch (e) {
		// @ts-expect-error
		t.equal(e.code, 'ERR_INVALID_ARG_VALUE');
		t.equal(isParseArgsError(e), true, 'invalid argument config value');
	}

	try {
		parseArgs({ args: ['foo'], allowPositionals: false });
		t.fail();
	} catch (e) {
		// @ts-expect-error
		t.equal(e.code, 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL');
		t.equal(isParseArgsError(e), true, 'unexpected positional');
	}

	t.end();
});