Mocha: how to run multiple JS test files in a separate working environment

I am new to Mocha, so this may be a trivial question, but have not yet found the answer:

I have a simple NodeJS project with the underlying 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" } } 

and the following test files in the test folder:

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(); }); }); 

when I run the test on npm, the first test succeeds and the second fails as shown below

 ie-macp-davidt:crap davide_talesco$ npm test > pc-lib@1.0.0 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. 

it’s pretty clear that the tests work under the same process ... my question is: how can I make them work under completely separate processes so that everyone can set their own environment?

Thanks,

David

+6
source share
3 answers

One of the easiest ways is to use the Unix find :

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

I would recommend using local mocha binaries to avoid problems if it is not installed globally:

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

If you want to add this to package.json, note that the backslash must be escaped:

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

If you want to interrupt testing as soon as the test file fails, you can do this as follows:

 find ./test -type f -name "*.js" -exec sh -c 'for n; do ./node_modules/.bin/mocha "$n" || exit 1; done' sh {} + 
0
source

Alternatively, you can use mocha-parallel-tests .

To install: https://www.npmjs.com/package/mocha-parallel-tests

Use:

  "scripts": { "test": "mocha-parallel-tests" }, 

The nice thing is that this is the right mocha slider, so you can customize reports and transfer standard mocha settings, such as collateral.

0
source

Source: https://habr.com/ru/post/1270337/


All Articles