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?