I am writing test cases for my Node.js application using Mocha. The test cases need an API key as an extra input option or parameter. The API key is private, so I don\'t wan
A simple way, using process.argv that contain the command line args
$ mocha -w test/*.js --KEY=YOUR_VALUE
Later, you can get YOUR_VALUE
in your code:
let LAST_PARAM = process.argv[process.argv.length-1]
let PARAM_NAME = LAST_PARAM.split("=")[0].replace("--","")
let PARAM_VALUE = LAST_PARAM.split("=")[1]
console.log("KEY: ", PARAM_VALUE)
To see all process.argv
:
process.argv.forEach((value, index) => {
console.log(`process.argv[${index}]: ${value}`);
})
Output:
$ mocha -w test/*.js --KEY=YOUR_VALUE
KEY: YOUR_VALUE
process.argv[0]: /usr/local/bin/node
process.argv[1]: /Users/pabloin/.npm-packages/lib/node_modules/mocha/bin/_mocha
process.argv[2]: -w
process.argv[3]: test/tt.js
process.argv[4]: test/tt2.js
process.argv[5]: --KEY=YOUR_VALUE
KEY: YOUR_VALUE
process.argv[0]: /usr/local/bin/node
process.argv[1]: /Users/pabloin/.npm-packages/lib/node_modules/mocha/bin/_mocha
process.argv[2]: -w
process.argv[3]: test/tt.js
process.argv[4]: test/tt2.js
process.argv[5]: --KEY=YOUR_VALUE