Skip to content

Commit

Permalink
fix: re-add options to check callback (#2079)
Browse files Browse the repository at this point in the history
  • Loading branch information
jly36963 committed Nov 30, 2021
1 parent c4d25b8 commit e75319d
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/yargs-factory.ts
Expand Up @@ -293,7 +293,10 @@ export class YargsInstance {
this[kTrackManuallySetKeys](keys);
return this;
}
check(f: (argv: Arguments) => any, global?: boolean): YargsInstance {
check(
f: (argv: Arguments, options: Options) => any,
global?: boolean
): YargsInstance {
argsert('<function> [boolean]', [f, global], arguments.length);
this.middleware(
(
Expand All @@ -304,7 +307,7 @@ export class YargsInstance {
Partial<Arguments> | Promise<Partial<Arguments>> | any
>(
() => {
return f(argv);
return f(argv, _yargs.getOptions());
},
(result: any): Partial<Arguments> | Promise<Partial<Arguments>> => {
if (!result) {
Expand Down
90 changes: 90 additions & 0 deletions test/validation.cjs
Expand Up @@ -14,6 +14,96 @@ describe('validation tests', () => {
yargs.getInternalMethods().reset();
});

describe('check', () => {
it('fails if error is thrown in check callback', done => {
yargs
.command(
'$0',
'default command desc',
yargs =>
yargs
.option('name', {
describe: 'name desc',
type: 'string',
alias: 'n',
})
.check(argv => {
const {name} = argv;
if (typeof name !== 'string' || !name.length) {
throw new Error('Option "name" must be a non-empty string');
}
return true;
}),
() => {
expect.fail();
}
)
.fail(() => {
return done();
})
.parse('--name');
});

it('does not fail if error is not thrown in check callback, and true is returned', () => {
yargs
.command(
'$0',
'default command desc',
yargs =>
yargs
.option('name', {
describe: 'version desc',
type: 'string',
alias: 'n',
})
.check(argv => {
const {name} = argv;
if (typeof name !== 'string' || !name.length) {
throw new Error('Option "name" must be a non-empty string');
}
return true;
}),
argv => argv
)
.fail(() => {
expect.fail();
})
.parse('--name Itachi');
});

it('callback has access to options', () => {
yargs
.command(
'$0',
'default command desc',
yargs =>
yargs
.option('name', {
describe: 'name desc',
type: 'string',
alias: 'n',
})
.check((_, options) => {
if (
typeof options !== 'object' ||
!Object.prototype.hasOwnProperty.call(options, 'string') ||
!options.string.includes('name')
) {
throw new Error(
'Check callback should have access to options'
);
}
return true;
}),
argv => argv
)
.fail(() => {
expect.fail();
})
.parse('--name Itachi');
});
});

describe('implies', () => {
const implicationsFailedPattern = new RegExp(
english['Implications failed:']
Expand Down

0 comments on commit e75319d

Please sign in to comment.