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
Take a look at the optimist module by Substack and nconf from flatiron. A lot of my tests depend on external parameters and the optimist and nconf modules makes it easy to load configuration options from a json file
In your test command pass the path to the config.json file
test command
api-test.js
config.json
Alternative
Another pattern I have been using recently is the config module. You can specify a
./config/default.yml
file for running regularly and a./config/test.yml
file for tests.When running your test suite, export NODE_ENV=test and the config module will load
test.yml
In your code it is easy to access the configuration object
An easy way to set NODE_ENV=test is by running your tests with a makefile. Run all your tests via
make test
. To run a single test executemake one NAME=test/unit/sample-test.js
Sample makefile
The other answers are limited in that they do not support code execution prior to running your test suite. They only support passing parameters.
This answer supports code execution BEFORE your test suite is executed and is fully documented by mocha
mocha docs: http://unitjs.com/guide/mocha.html#mocha-opts
create ./test/mocha.opts
create ./server.bootstrap.js
create ./test/test.bootstrap.js
finally in your server.js:
DONE!
The code in the server bootstrap will be executed prior to testing and server execution (npm start and npm test)
The code in the test bootstrap will only be executed prior to testing (npm test)
Thanks to @damianfabian for this one - see How to initialise a global variable in unit test runs?
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:
package.json:
test.js