Test suite fails when commander error is thrown in jest even with catch

69 views Asked by At

I have written a script using commander. When testing this script for logical throw that cause errors I cannot seem to trap the commander error that gets thrown

Test Logic

    expect.assertions(1)

    try {
      const program = createProgram()
      program.exitOverride()
      await program.parse(['npx', 'bomci', 'artefact-save', 'some-file', 'some-folder', 'some-location' ])
    } catch(err) {
      expect(true).toBe(true)
      // put assertions here
    }

I would expect the error to be caught in the catch statement but instead I get:

CommanderError: bomci artefact-save expects the environment variable {ARTIFACTORY_USER} to be set.
    at Command._exit (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:449:26)
    at Command.error (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1608:10)
    at Command.<anonymous> (/home/mbell/projects/bom-pipeline-utils/src/index.ts:25:21)
    at Command.listener [as _actionHandler] (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:482:17)
    at /home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1300:65
    at Command._chainOrCall (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1197:12)
    at Command._parseCommand (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1300:27)
    at /home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1081:27
    at Command._chainOrCall (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1197:12)
    at Command._dispatchSubcommand (/home/mbell/projects/bom-pipeline-utils/node_modules/commander/lib/command.js:1077:23) {
  code: 'commander.error',
  exitCode: 9,
  nestedError: undefined
}

The line triggering the error is:

      let artiCreds
      try {
        artiCreds = getArtifactoryCredentials('artefact-save')
      } catch (err) {
        program.error(err.message, { exitCode: 9 })
      }

So why is my error not getting caught and how can I trap this error for my testing?

1

There are 1 answers

1
user3559247 On

After a lot of digging around I found that for commander if your action is asynchronous you need to parseAsync instead of parse

The following test now works correctly for me:

    const program = createProgram()
    program.exitOverride()
    expect(() => program.parseAsync(['npx', 'bomci', 'artefact-save', 'some-file', 'some-folder', 'some-location' ]))
      .rejects.toEqual(new CommanderError(9 , '', 'bomci artefact-save expects the environment variable {ARTIFACTORY_USER} to be set.'))