code

추가 옵션 또는 매개 변수가있는 모카 테스트

codestyles 2020. 10. 18. 17:57
반응형

추가 옵션 또는 매개 변수가있는 모카 테스트


Mocha를 사용하여 Node.js 애플리케이션에 대한 테스트 케이스를 작성하고 있습니다. 테스트 케이스에는 추가 입력 옵션 또는 매개 변수로 API 키가 필요합니다. API 키는 비공개이므로 모든 사람이 GitHub에서 볼 수 있으므로 테스트 파일에 직접 포함하고 싶지 않습니다. Mocha에 사용할 수있는 몇 가지 옵션이 있습니다.

http://mochajs.org/#usage

그러나 테스터가 명령 줄에서 테스트를 위해 자체 API 키를 지정할 수 있도록 매개 변수를 포함 할 수 있습니까? 예 :

./node_modules/mocha/bin/mocha test/*.js --key YOUR_KEY

Mocha 자체가 테스트에 추가 매개 변수를 전달하는 것을 지원하지는 않지만 환경 변수를 사용할 수 있습니다.

env KEY=YOUR_KEY mocha test/*.js # assumes some sort of Unix-type OS.

그리고 테스트 파일에서 읽으십시오.

var key = process.env.KEY;

flatiron의 Substack과 nconfoptimist 모듈을 살펴보십시오 . 내 테스트의 대부분은 외부 매개 변수에 의존하며 optimist 및 nconf 모듈을 사용하면 json 파일에서 구성 옵션을 쉽게로드 할 수 있습니다.

테스트 명령에서 config.json 파일의 경로를 전달하십시오.

테스트 명령

mocha test/api-test.js --config=/path/to/config.json --reporter spec

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
  }
}

대안

최근에 사용한 또 다른 패턴은 구성 모듈입니다. ./config/default.yml정기적으로 실행할 ./config/test.yml파일과 테스트 용 파일을 지정할 수 있습니다 .

테스트 스위트를 실행할 때 NODE_ENV = test를 내 보내면 구성 모듈이로드됩니다. test.yml

코드에서 구성 객체에 쉽게 액세스 할 수 있습니다.

var config = require('config')

// config now contains your actual configuration values as determined by the process.env.NODE_ENV
var apiKey = config.api.key

NODE_ENV = test를 설정하는 쉬운 방법은 메이크 파일로 테스트를 실행하는 것입니다. 를 통해 모든 테스트를 실행하십시오 make test. 단일 테스트를 실행하려면make one NAME=test/unit/sample-test.js

샘플 메이크 파일

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

이 스레드에서 언급 한 process.argv [index] 메소드와 유사한 매개 변수를 전달하는 가장 쉬운 방법 중 하나는 npm 구성 변수를 사용하는 것입니다. 이렇게하면 변수 이름을 좀 더 명확하게 볼 수 있습니다.

테스트 명령 :

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"

Mocha로이 작업을 수행하는 지원되는 방법이 없습니다. 제안 된 방법은 파일 (예 : config.json)을 사용하고 필요로하고 다른 사람이 변경하도록하는 것입니다.

즉, 명령 줄 끝 (테스트 할 파일 이후)에서 키를 전달하고 사용하는 경우 process.argv를 사용하여 사용할 수 있어야합니다 (사용하지 않는 경우-또는 일반 파일 이후가 아닌 경우) 이름, 그러면 모카가 실패합니다).

을 실행 ./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 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

--recursive
--reporter spec
--require ./server.bootstrap
--require ./test/test.bootstrap

create ./server.bootstrap.js

global.appRoot = require('app-root-path');
// any more server init code

create ./test/test.bootstrap.js

process.env.NODE_ENV='test';
// any more test specific init code

finally in your 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)

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?


You can pass an argument to mocha test script using 'minimist' module. Install with 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);

I could send parameter thought 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

var yourParam = process.env.yourParam;

A simple way, using process.argv that contain the command line args

$ mocha  -w test/*.js --KEY=YOUR_KEY

Later, you can get YOUR_KEY 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_KEY

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_KEY

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_KEY

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

참고URL : https://stackoverflow.com/questions/16144455/mocha-tests-with-extra-options-or-parameters

반응형