How to run some initialization code with mocha

I know about before , beforeEach , after and afterEach , but how do I run the code before ALL tests.

In other words, I am files like this

 test test1.js test2.js test3.js 

I run tests with

 mocha --recursive 

I do not want to put before in every test file. I need beforeAllTests or --init=setup.js , or something that I can execute JavaScript before all tests are completed. In this particular case, I have to configure the system registration module before the tests run

Is there a way to call some init function that runs before all tests?

+5
source share
3 answers

If only an initialization code is required, mocha -r ./init may be enough mocha -r ./init . even put it in test/mocha.opts

 --require ./test/init --ui tdd 

But if you need tearing action, a dilemma arises, for example:

 var app = require('../app.js'); app.listen(process.env.WEB_PORT); after(function(done) { var db = mongoskin.db(process.env.DB_URL, {safe:true}); db.dropDatabase(function(err) { expect(err).to.not.be.ok(); db.close(done); }); }); 

You will receive an error message:

ReferenceError: after is not defined

I think mocha was not initialized during the '--require' processing.

+4
source

I realized this recently in our node application:

  • reorganize the test files as shown below (only one js file "bootstrap.js" in the test /, and put all the test files in subfolders):
      test
        β”œβ”€β”€unit
        β”‚ β”œβ”€β”€ test1
        β”‚ β”œβ”€β”€ test2
        β”‚ └── ...
        β”œβ”€β”€integeration
        β”‚ β”œβ”€β”€ test1
        β”‚ β”œβ”€β”€ test2
        β”‚ └── ...
        β”œβ”€β”€ bootstrap.js
        └── mocha.opts
    
  • put '--recursive' in mocha.opts
  • enter the initialization code in bootstrap.js (global before / after work here!)

done.

+3
source

This is the official solution for mocha:

Mocha tests with additional parameters or parameters

It allows you to define code that can be:

1 - Runs before npm starts and npm checks

2 - Run only before npm check

+1
source

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


All Articles