Skip to content
Myr

command.exitOverride.test.js

This file

Path

tests/command.exitOverride.test.js

460 lines · 11.9 KiB · JavaScript

Last changed by

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

History of this file

Take it

1const commander = require('../');2const path = require('path');34// Test details of the exitOverride errors.5// The important checks are the exitCode and code which are intended to be stable for6// semver minor versions. For now, also testing the error.message and that output occurred7// to detect accidental changes in behaviour.89/* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "expectCommanderError"] }] */1011function expectCommanderError(err, exitCode, code, message) {12  expect(err).toBeInstanceOf(commander.CommanderError);13  expect(err.exitCode).toBe(exitCode);14  expect(err.code).toBe(code);15  expect(err.message).toBe(message);16}1718describe('.exitOverride and error details', () => {19  // Use internal knowledge to suppress output to keep test output clean.20  let stderrSpy;2122  beforeAll(() => {23    stderrSpy = jest24      .spyOn(process.stderr, 'write')25      .mockImplementation(() => {});26  });2728  afterEach(() => {29    stderrSpy.mockClear();30  });3132  afterAll(() => {33    stderrSpy.mockRestore();34  });3536  test('when specify unknown program option then throw CommanderError', () => {37    const program = new commander.Command();38    program.exitOverride();3940    let caughtErr;41    try {42      program.parse(['node', 'test', '-m']);43    } catch (err) {44      caughtErr = err;45    }4647    expect(stderrSpy).toHaveBeenCalled();48    expectCommanderError(49      caughtErr,50      1,51      'commander.unknownOption',52      "error: unknown option '-m'",53    );54  });5556  test('when specify unknown command then throw CommanderError', () => {57    const program = new commander.Command();58    program.name('prog').exitOverride().command('sub');5960    let caughtErr;61    try {62      program.parse(['node', 'test', 'oops']);63    } catch (err) {64      caughtErr = err;65    }6667    expect(stderrSpy).toHaveBeenCalled();68    expectCommanderError(69      caughtErr,70      1,71      'commander.unknownCommand',72      "error: unknown command 'oops'",73    );74  });7576  // Same error as above, but with custom handler.77  test('when supply custom handler then throw custom error', () => {78    const customError = new commander.CommanderError(79      123,80      'custom-code',81      'custom-message',82    );83    const program = new commander.Command();84    program.exitOverride((_err) => {85      throw customError;86    });8788    let caughtErr;89    try {90      program.parse(['node', 'test', '-m']);91    } catch (err) {92      caughtErr = err;93    }9495    expectCommanderError(96      caughtErr,97      customError.exitCode,98      customError.code,99      customError.message,100    );101  });102103  test('when specify option without required value then throw CommanderError', () => {104    const optionFlags = '-p, --pepper <type>';105    const program = new commander.Command();106    program.exitOverride().option(optionFlags, 'add pepper');107108    let caughtErr;109    try {110      program.parse(['node', 'test', '--pepper']);111    } catch (err) {112      caughtErr = err;113    }114115    expect(stderrSpy).toHaveBeenCalled();116    expectCommanderError(117      caughtErr,118      1,119      'commander.optionMissingArgument',120      `error: option '${optionFlags}' argument missing`,121    );122  });123124  test('when specify command without required argument then throw CommanderError', () => {125    const program = new commander.Command();126    program127      .exitOverride()128      .command('compress <arg-name>')129      .action(() => {});130131    let caughtErr;132    try {133      program.parse(['node', 'test', 'compress']);134    } catch (err) {135      caughtErr = err;136    }137138    expect(stderrSpy).toHaveBeenCalled();139    expectCommanderError(140      caughtErr,141      1,142      'commander.missingArgument',143      "error: missing required argument 'arg-name'",144    );145  });146147  test('when specify program without required argument and no action handler then throw CommanderError', () => {148    const program = new commander.Command();149    program.exitOverride().argument('<arg-name>');150151    let caughtErr;152    try {153      program.parse(['node', 'test']);154    } catch (err) {155      caughtErr = err;156    }157158    expect(stderrSpy).toHaveBeenCalled();159    expectCommanderError(160      caughtErr,161      1,162      'commander.missingArgument',163      "error: missing required argument 'arg-name'",164    );165  });166167  test('when specify excess argument then throw CommanderError', () => {168    const program = new commander.Command();169    program170      .exitOverride()171      .allowExcessArguments(false)172      .action(() => {});173174    let caughtErr;175    try {176      program.parse(['node', 'test', 'excess']);177    } catch (err) {178      caughtErr = err;179    }180181    expect(stderrSpy).toHaveBeenCalled();182    expectCommanderError(183      caughtErr,184      1,185      'commander.excessArguments',186      'error: too many arguments. Expected 0 arguments but got 1.',187    );188  });189190  test('when specify command with excess argument then throw CommanderError', () => {191    const program = new commander.Command();192    program193      .exitOverride()194      .command('speak')195      .allowExcessArguments(false)196      .action(() => {});197198    let caughtErr;199    try {200      program.parse(['node', 'test', 'speak', 'excess']);201    } catch (err) {202      caughtErr = err;203    }204205    expect(stderrSpy).toHaveBeenCalled();206    expectCommanderError(207      caughtErr,208      1,209      'commander.excessArguments',210      "error: too many arguments for 'speak'. Expected 0 arguments but got 1.",211    );212  });213214  test('when specify --help then throw CommanderError', () => {215    const writeSpy = jest216      .spyOn(process.stdout, 'write')217      .mockImplementation(() => {});218    const program = new commander.Command();219    program.exitOverride();220221    let caughtErr;222    try {223      program.parse(['node', 'test', '--help']);224    } catch (err) {225      caughtErr = err;226    }227228    expectCommanderError(229      caughtErr,230      0,231      'commander.helpDisplayed',232      '(outputHelp)',233    );234    writeSpy.mockRestore();235  });236237  test('when executable subcommand and no command specified then throw CommanderError', () => {238    const program = new commander.Command();239    program.exitOverride().command('compress', 'compress description');240241    let caughtErr;242    try {243      program.parse(['node', 'test']);244    } catch (err) {245      caughtErr = err;246    }247248    expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');249  });250251  test('when specify --version then throw CommanderError', () => {252    const stdoutSpy = jest253      .spyOn(process.stdout, 'write')254      .mockImplementation(() => {});255    const myVersion = '1.2.3';256    const program = new commander.Command();257    program.exitOverride().version(myVersion);258259    let caughtErr;260    try {261      program.parse(['node', 'test', '--version']);262    } catch (err) {263      caughtErr = err;264    }265266    expectCommanderError(caughtErr, 0, 'commander.version', myVersion);267    stdoutSpy.mockRestore();268  });269270  test('when executableSubcommand succeeds then call exitOverride', async () => {271    expect.hasAssertions();272    const pm = path.join(__dirname, 'fixtures/pm');273    const program = new commander.Command();274    await new Promise((resolve) => {275      program276        .exitOverride((err) => {277          expectCommanderError(278            err,279            0,280            'commander.executeSubCommandAsync',281            '(close)',282          );283          resolve();284        })285        .command('silent', 'description');286      program.parse(['node', pm, 'silent']);287    });288  });289290  test('when mandatory program option missing then throw CommanderError', () => {291    const optionFlags = '-p, --pepper <type>';292    const program = new commander.Command();293    program.exitOverride().requiredOption(optionFlags, 'add pepper');294295    let caughtErr;296    try {297      program.parse(['node', 'test']);298    } catch (err) {299      caughtErr = err;300    }301302    expectCommanderError(303      caughtErr,304      1,305      'commander.missingMandatoryOptionValue',306      `error: required option '${optionFlags}' not specified`,307    );308  });309310  test('when option argument not in choices then throw CommanderError', () => {311    const optionFlags = '--colour <shade>';312    const program = new commander.Command();313    program314      .exitOverride()315      .addOption(new commander.Option(optionFlags).choices(['red', 'blue']));316317    let caughtErr;318    try {319      program.parse(['--colour', 'green'], { from: 'user' });320    } catch (err) {321      caughtErr = err;322    }323324    expectCommanderError(325      caughtErr,326      1,327      'commander.invalidArgument',328      "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.",329    );330  });331332  test('when command argument not in choices then throw CommanderError', () => {333    const program = new commander.Command();334    program335      .exitOverride()336      .addArgument(new commander.Argument('<shade>').choices(['red', 'blue']))337      .action(() => {});338339    let caughtErr;340    try {341      program.parse(['green'], { from: 'user' });342    } catch (err) {343      caughtErr = err;344    }345346    expectCommanderError(347      caughtErr,348      1,349      'commander.invalidArgument',350      "error: command-argument value 'green' is invalid for argument 'shade'. Allowed choices are red, blue.",351    );352  });353354  test('when custom processing for option throws InvalidArgumentError then catch CommanderError', () => {355    function justSayNo(value) {356      throw new commander.InvalidArgumentError('NO');357    }358    const optionFlags = '--colour <shade>';359    const program = new commander.Command();360    program.exitOverride().option(optionFlags, 'specify shade', justSayNo);361362    let caughtErr;363    try {364      program.parse(['--colour', 'green'], { from: 'user' });365    } catch (err) {366      caughtErr = err;367    }368369    expectCommanderError(370      caughtErr,371      1,372      'commander.invalidArgument',373      "error: option '--colour <shade>' argument 'green' is invalid. NO",374    );375  });376377  test('when custom processing for argument throws InvalidArgumentError then catch CommanderError', () => {378    function justSayNo(value) {379      throw new commander.InvalidArgumentError('NO');380    }381    const program = new commander.Command();382    program383      .exitOverride()384      .argument('[n]', 'number', justSayNo)385      .action(() => {});386387    let caughtErr;388    try {389      program.parse(['green'], { from: 'user' });390    } catch (err) {391      caughtErr = err;392    }393394    expectCommanderError(395      caughtErr,396      1,397      'commander.invalidArgument',398      "error: command-argument value 'green' is invalid for argument 'n'. NO",399    );400  });401402  test('when has conflicting option then throw CommanderError', () => {403    const program = new commander.Command();404    program405      .exitOverride()406      .addOption(new commander.Option('--silent'))407      .addOption(new commander.Option('--debug').conflicts(['silent']));408409    let caughtErr;410    try {411      program.parse(['--debug', '--silent'], { from: 'user' });412    } catch (err) {413      caughtErr = err;414    }415416    expectCommanderError(417      caughtErr,418      1,419      'commander.conflictingOption',420      "error: option '--debug' cannot be used with option '--silent'",421    );422  });423424  test('when call error() then throw CommanderError', () => {425    const program = new commander.Command();426    program.exitOverride();427428    let caughtErr;429    try {430      program.error('message');431    } catch (err) {432      caughtErr = err;433    }434435    expectCommanderError(caughtErr, 1, 'commander.error', 'message');436  });437});438439test('when no override and error then exit(1)', () => {440  const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});441  const program = new commander.Command();442  program.configureOutput({ outputError: () => {} });443  program.parse(['--unknownOption'], { from: 'user' });444  expect(exitSpy).toHaveBeenCalledWith(1);445  exitSpy.mockRestore();446});447448test('when custom processing throws custom error then throw custom error', () => {449  function justSayNo(value) {450    throw new Error('custom');451  }452  const program = new commander.Command();453  program454    .exitOverride()455    .option('-s, --shade <value>', 'specify shade', justSayNo);456457  expect(() => {458    program.parse(['--shade', 'green'], { from: 'user' });459  }).toThrow('custom');460});