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
I have been reading quite some answers, most of them more complex than the actual solution has to be.
Let's say I have config.yml
or config.json
. In my case it's a YAML file.
First of all I install the yamljs
dependency. It has a function called load
.
Basically what I do:
const YAML = require('yamljs');
const ymlConfig = YAML.load('./config.yml');
Then I go for:
process.env.setting1 = ymlConfig.setting1;
process.env.setting2 = ymlConfig.setting2;
And of course - this is all done in your test file.
if you are debugging/testing with Mocha sidebar (VS Code extension), just put it:
{
"mocha.env": {
"KEY": "YOUR_KEY",
"MY_VARIABLE": "MY VALUE"
}
}
at .vscode/settings.json
One of the easiest ways to pass parameters similar to the process.argv[index] method mentioned in this thread is using the npm config variables. This allows you to see the variable name a little more clearly:
test command:
npm --somevariable=myvalue run mytest
package.json:
"scripts": {
"mytest": "mocha ./test.js" }
test.js
console.log(process.env.npm_config_somevariable) // should evaluate to "myvalue"