node.js 带有额外选项或参数的摩卡测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16144455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mocha tests with extra options or parameters
提问by afterglowlee
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:
我正在使用 Mocha 为我的 Node.js 应用程序编写测试用例。测试用例需要一个 API 密钥作为额外的输入选项或参数。API 密钥是私有的,所以我不想将它直接包含在测试文件中,因为每个人都可以在 GitHub 上看到它。我知道 Mocha 有一些可用的选项:
But is it possible to include some parameters to let testers specify their own API key for the test in the commandline? Such as:
但是是否可以包含一些参数让测试人员在命令行中为测试指定他们自己的 API 密钥?如:
./node_modules/mocha/bin/mocha test/*.js --key YOUR_KEY
回答by robertklep
I don't think Mocha itself supports passing extra parameters to your tests, but you could use environment variables:
我不认为 Mocha 本身支持将额外的参数传递给您的测试,但您可以使用环境变量:
env KEY=YOUR_KEY mocha test/*.js # assumes some sort of Unix-type OS.
And read them in your test files:
并在您的测试文件中阅读它们:
var key = process.env.KEY;
回答by Noah
Take a look at the optimistmodule by Substack and nconffrom 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
看看Substack的optimist模块和flatiron 的 nconf。我的很多测试都依赖于外部参数,并且 optimist 和 nconf 模块可以轻松地从 json 文件加载配置选项
In your test command pass the path to the config.json file
在您的测试命令中传递 config.json 文件的路径
test command
测试命令
mocha test/api-test.js --config=/path/to/config.json --reporter spec
api-test.js
api-test.js
var path = require('path')
var fs = require('fs')
var assert = require('assert')
var argv = require('optimist').demand('config').argv
var configFilePath = argv.config
assert.ok(fs.existsSync(configFilePath), 'config file not found at path: ' + configFilePath)
var config = require('nconf').env().argv().file({file: configFilePath})
var apiConfig = config.get('api')
var apiKey = apiConfig.key
config.json
配置文件
{
"api": {
"key": "fooKey",
"host": "example.com",
"port": 9000
}
}
Alternative
选择
Another pattern I have been using recently is the configmodule. You can specify a ./config/default.ymlfile for running regularly and a ./config/test.ymlfile for tests.
我最近使用的另一种模式是配置模块。您可以指定一个./config/default.yml用于定期运行的./config/test.yml文件和一个用于测试的文件。
When running your test suite, export NODE_ENV=test and the config module will load test.yml
运行测试套件时,导出 NODE_ENV=test 并且配置模块将加载 test.yml
In your code it is easy to access the configuration object
在您的代码中很容易访问配置对象
var config = require('config')
// config now contains your actual configuration values as determined by the process.env.NODE_ENV
var apiKey = config.api.key
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 execute make one NAME=test/unit/sample-test.js
设置 NODE_ENV=test 的一种简单方法是使用 makefile 运行测试。通过make test. 运行单个测试执行make one NAME=test/unit/sample-test.js
Sample makefile
示例生成文件
MOCHA?=node_modules/.bin/mocha
REPORTER?=spec
GROWL?=--growl
FLAGS=$(GROWL) --reporter $(REPORTER) --colors --bail
test:
@NODE_ENV="test" \
$(MOCHA) $(shell find test -name "*-test.js") $(FLAGS)
one:
@NODE_ENV="test" \
$(MOCHA) $(NAME) $(FLAGS)
unit:
@NODE_ENV="test" \
$(MOCHA) $(shell find test/unit -name "*-test.js") $(FLAGS)
integration:
@NODE_ENV="test" \
$(MOCHA) $(shell find test/integration -name "*-test.js") $(FLAGS)
acceptance:
@NODE_ENV="test" \
$(MOCHA) $(shell find test/acceptance -name "*-test.js") $(FLAGS)
.PHONY: test
回答by Adam Levine
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:
传递类似于该线程中提到的 process.argv[index] 方法的参数的最简单方法之一是使用 npm 配置变量。这使您可以更清楚地看到变量名称:
test command:
测试命令:
npm --somevariable=myvalue run mytest
package.json:
包.json:
"scripts": {
"mytest": "mocha ./test.js" }
test.js
测试.js
console.log(process.env.npm_config_somevariable) // should evaluate to "myvalue"
回答by danday74
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 完整记录
mocha docs: http://unitjs.com/guide/mocha.html#mocha-opts
摩卡文档:http: //unitjs.com/guide/mocha.html#mocha-opts
create ./test/mocha.opts
创建 ./test/mocha.opts
--recursive
--reporter spec
--require ./server.bootstrap
--require ./test/test.bootstrap
create ./server.bootstrap.js
创建 ./server.bootstrap.js
global.appRoot = require('app-root-path');
// any more server init code
create ./test/test.bootstrap.js
创建 ./test/test.bootstrap.js
process.env.NODE_ENV='test';
// any more test specific init code
finally in your server.js:
最后在你的 server.js 中:
require('./server.bootstrap');
DONE!
完毕!
The code in the server bootstrap will be executed prior to testing and server execution (npm start and npm test)
服务器引导程序中的代码将在测试和服务器执行之前执行(npm start 和 npm test)
The code in the test bootstrap will only be executed prior to testing (npm test)
测试引导程序中的代码只会在测试之前执行(npm test)
Thanks to @damianfabian for this one - see How to initialise a global variable in unit test runs?
感谢@damianfabian 提供了这一点 - 请参阅如何在单元测试运行中初始化全局变量?
回答by Alon Bar David
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.
Mocha 没有支持的方法来做到这一点。建议的方法是使用一个文件(例如 config.json),要求它,然后让其他人更改它。
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).
话虽如此,如果您在命令行的末尾(在要测试的文件之后)传递您的密钥并使用 - 它应该可以使用 process.argv (如果您不使用 - 或者它不在常规文件之后名称,那么摩卡咖啡将失败)。
if you run ./node_modules/mocha/bin/mocha --reporter spec test.js --apiKey=someKey, and test.js contains the code:
如果您运行./node_modules/mocha/bin/mocha --reporter spec test.js --apiKey=someKey,并且 test.js 包含代码:
var assert = require("assert")
describe("testy", function () {
it("shouldy", function (done) {
var value;
for (var index in process.argv) {
var str = process.argv[index];
if (str.indexOf("--apiKey") == 0) {
value = str.substr(9);
}
}
assert.equal(value,"someKey")
done();
})
})
the test should pass
测试应该通过
回答by David Douglas
You can pass an argument to mocha test script using 'minimist' module.
Install with npm install minimist
您可以使用“minimist”模块将参数传递给 mocha 测试脚本。安装npm install minimist
Terminal:
终端:
mocha test.js --config=VALUE
Mocha node script:
摩卡节点脚本:
var argv = require('minimist')(process.argv.slice(2));
console.log('config', argv.config);
回答by Pablo Ezequiel
A simple way, using process.argv that contain the command line args
一个简单的方法,使用包含命令行参数的 process.argv
$ mocha -w test/*.js --KEY=YOUR_VALUE
Later, you can get YOUR_KEY in your code:
稍后,您可以在代码中获取 YOUR_KEY:
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
process.argv.forEach((value, index) => {
console.log(`process.argv[${index}]: ${value}`);
})
Output
输出
$ mocha -w test/*.js --KEY=YOUR_VALUE
KEY: YOUR_KEY
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_KEY
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
回答by SM Adnan
I could send parameter thought mochaStream (require('spawn-mocha-parallel').mochaStream).
我可以发送参数认为 mochaStream (require('spawn-mocha-parallel').mochaStream)。
like:
喜欢:
var mochaStream = require('spawn-mocha-parallel').mochaStream;
var mocha = mochaStream({
env: function(){
return {yourParam: 'value'}
}
});
return gulp.src('test/**/*-specs.js', {read: false})
.pipe(mochaStream)
.on('error', console.warn.bind(console));
Inside ..spec.js file
..spec.js 文件内
var yourParam = process.env.yourParam;
回答by Bilger Yahov
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.ymlor config.json. In my case it's a YAML file.
假设我有config.yml或config.json。就我而言,它是一个 YAML 文件。
First of all I install the yamljsdependency. It has a function called load.
首先我安装yamljs依赖项。它有一个名为load.
Basically what I do:
基本上我做什么:
const YAML = require('yamljs');
const ymlConfig = YAML.load('./config.yml');
const YAML = require('yamljs');
const ymlConfig = YAML.load('./config.yml');
Then I go for:
然后我去:
process.env.setting1 = ymlConfig.setting1;
process.env.setting2 = ymlConfig.setting2;
process.env.setting1 = ymlConfig.setting1;
process.env.setting2 = ymlConfig.setting2;
And of course - this is all done in your test file.
当然 - 这一切都在您的测试文件中完成。
回答by fsilva
if you are debugging/testing with Mocha sidebar (VS Code extension), just put it:
如果您正在使用 Mocha 侧边栏(VS Code 扩展)进行调试/测试,只需输入:
{
"mocha.env": {
"KEY": "YOUR_KEY",
"MY_VARIABLE": "MY VALUE"
}
}
at .vscode/settings.json
在 .vscode/settings.json

