Skip to content

Commit

Permalink
Fix flag default values validation (#238)
Browse files Browse the repository at this point in the history
  • Loading branch information
istandre committed May 4, 2023
1 parent 525e442 commit c3bf62b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
2 changes: 1 addition & 1 deletion source/options.js
Expand Up @@ -27,7 +27,7 @@ const validateOptions = options => {
},
},
defaultNotInChoices: {
filter: ([, flag]) => flag.default && Array.isArray(flag.choices) && [flag.default].flat().every(value => flag.choices.includes(value)),
filter: ([, flag]) => flag.default && Array.isArray(flag.choices) && ![flag.default].flat().every(value => flag.choices.includes(value)),
message: flagKeys => `Each value of the option \`default\` must exist within the option \`choices\`. Invalid flags: ${joinFlagKeys(flagKeys)}`,
},
},
Expand Down
43 changes: 40 additions & 3 deletions test/choices.js
Expand Up @@ -177,8 +177,8 @@ test('choices - choices must be of the same type', t => {
}, {message: 'Each value of the option `choices` must be of the same type as its flag. Invalid flags: (`--number`, type: \'number\'), (`--boolean`, type: \'boolean\')'});
});

test('choices - default must only include valid choices', t => {
t.throws(() => {
test('choices - success when each value of default exist within the option choices', t => {
t.notThrows(() => {
meow({
importMeta,
flags: {
Expand All @@ -187,7 +187,44 @@ test('choices - default must only include valid choices', t => {
choices: [1, 2, 3],
default: 1,
},
string: {
type: 'string',
choices: ['dog', 'cat', 'unicorn'],
default: 'dog',
},
multiString: {
type: 'string',
choices: ['dog', 'cat', 'unicorn'],
default: ['dog', 'cat'],
isMultiple: true,
},
},
});
});
});

test('choices - throws when default does not only include valid choices', t => {
t.throws(() => {
meow({
importMeta,
flags: {
number: {
type: 'number',
choices: [1, 2, 3],
default: 8,
},
string: {
type: 'string',
choices: ['dog', 'cat'],
default: 'unicorn',
},
multiString: {
type: 'string',
choices: ['dog', 'cat'],
default: ['dog', 'unicorn'],
isMultiple: true,
},
},
});
}, {message: 'Each value of the option `default` must exist within the option `choices`. Invalid flags: `--number`'});
}, {message: 'Each value of the option `default` must exist within the option `choices`. Invalid flags: `--number`, `--string`, `--multiString`'});
});

0 comments on commit c3bf62b

Please sign in to comment.