1

I've recently introduced commander.js to a project and use it in various scripts to parse CLI arguments. I'll give one example of where it's been used:

const { program } = require('commander');

program
    .description('Import customers and accounts')
    .argument('[filePath]', 'Path to JSON file containing customers and accounts', `${path.resolve(__dirname)}/data/customers.json`)
    .action(filePath => {
        importCustomersAndAccounts(filePath)
        .catch((e) => {
            console.log(e);
            process.exit();
        })
        .finally(() => process.exit());
    })

program.parse();

This script itself isn't the issue, it works fine when run from the CLI. The issue happens when I run tests that use this same script. I have the test script setup in package.json as follows:

"test": "NODE_ENV=TESTING mocha --exit --require tests/setup.js 'tests/src/**/*.spec.js' 'tests/scripts/**/*.spec.js'"

When I run the tests, I immediately get this error:

error: unknown option '--exit'

Which is being thrown by commander, not mocha. So this option getting passed to mocha when running npm run test is getting to the script itself. I've confirmed this is what's happening, because when I chained .option('--exit') after the .description() in the commander code above, it then failed with

error: unknown option '--require'

So it's reaching the next option passed to mocha and then failing on whichever option is not defined in the script. How can I prevent these options from reaching the script itself and get them to simply be parsed by mocha?

  • 1
    I think you've to test whether your app is actually being called from the terminal and manually call the `program.parse()` with `process.argv`. Or may be like `if(process.env.NODE_ENV !== "TESTING") program.parse()`. – h-sifat Jan 26 '23 at 12:47
  • @h-sifat Yes, that seems to be what the issue was here. When conditionally calling `program.parse()` ensuring the script is being run from the CLI and not imported, there are no longer any errors. Please feel free to post this as an actual answer so I can accept it as correct. Thank you! – LiteralMetaphore Jan 26 '23 at 12:57
  • 1
    No, it's ok. I'm just glad that it fixed your problem. I'm happy of help. – h-sifat Jan 26 '23 at 13:09

0 Answers0