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 want to include it directly in the test files as everyone then can see it on GitHub. I know there are some options available for Mocha at:
But is it possible to include some parameters to let testers specify their own API key for the test in the commandline? Such as:
./node_modules/mocha/bin/mocha test/*.js --key YOUR_KEY
A simple way, using process.argv that contain the command line args
Later, you can get YOUR_KEY in your code:
To see all process.argv
Output
I could send parameter thought mochaStream (require('spawn-mocha-parallel').mochaStream).
like:
Inside ..spec.js file
I don't think Mocha itself supports passing extra parameters to your tests, but you could use environment variables:
And read them in your test files:
There's no supported way to do this with Mocha. the suggested way is to use a file (for instance config.json), require it, and let other people change it.
That being said, if you pass your key at the end of the commandline (after the file to test) and use -- it should be available using process.argv (if you don't use -- or it's not after a regular file name, then mocha will fail).
if you run
./node_modules/mocha/bin/mocha --reporter spec test.js --apiKey=someKey
, and test.js contains the code:the test should pass
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
orconfig.json
. In my case it's a YAML file.First of all I install the
yamljs
dependency. It has a function calledload
.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.
You can pass an argument to mocha test script using 'minimist' module. Install with
npm install minimist
Terminal:
Mocha node script: