2017-07-28 19 views
5

我是新來摩卡所以這可能可能是一個微不足道的問題,但不是可能尚未找到答案:摩卡:如何運行獨立的進程環境下的多個JS測試文件

我有一個簡單的項目的NodeJS與測試文件夾下的下面的package.json

{ 
    "name": "test", 
    "version": "1.0.0", 
    "description": "test", 
    "main": "index.js", 
    "scripts": { 
    "test": "mocha" 
    }, 
    "author": "davide talesco", 
    "license": "ISC", 
    "devDependencies": { 
    "chai": "^4.0.2", 
    "mocha": "^3.4.2" 
    } 
} 

和下面的兩個測試文件:

test1.js

process.env.NODE_ENV = 'test'; 

var chai = require('chai'); 
var should = chai.should(); 

describe('Test setProp', function(){ 
    it('env variable should be test', function(done){ 
    process.env.NODE_ENV.should.be.equal('test'); 
    return done(); 
    }); 
}); 

test2.js

process.env.NODE_ENV = 'prod'; 

var chai = require('chai'); 
var should = chai.should(); 

describe('Test setProp', function(){ 
    it('env variable should be prod', function(done){ 
    process.env.NODE_ENV.should.be.equal('prod'); 
    return done(); 
    }); 
}); 

當我運行NPM測試第一次測試成功地完成,而第二未能按以下

ie-macp-davidt:crap davide_talesco$ npm test 

> [email protected] test /Users/davide_talesco/development/crap 
> mocha 



    Test setProp 
    1) env variable should be test 

    Test setProp 
    ✓ env variable should be prod 


    1 passing (16ms) 
    1 failing 

    1) Test setProp env variable should be test: 

     AssertionError: expected 'prod' to equal 'test' 
     + expected - actual 

     -prod 
     +test 

     at Context.<anonymous> (test/test1.js:11:36) 



npm ERR! Test failed. See above for more details. 

它相當清楚的是,測試下運行相同的過程... 我的問題是:我如何讓它們在完全獨立的進程下運行,這樣每個人都可以設置自己的環境?

感謝,

達維德

回答

2

一個最簡單的方法是使用Unix的find命令:

find ./test -name '*.js' -exec mocha \{} \;

我建議使用本地mocha二進制文件,以避免麻煩它不是全球安裝的:

find ./test -name '*.js' -exec ./node_modules/.bin/mocha \{} \;

如果你想將它添加到的package.json,請注意,反斜槓需要轉義:

... 
"scripts": { 
    "test": "find ./test -name '*.js' -exec ./node_modules/.bin/mocha \\{} \\;" 
}, 
...