Brian
Brian

Reputation: 13583

mocha global `before` that executes only 1 time

I'm using mocha for node.js functional testing.

There are several files in my test.

How can I run a piece of code for only one time before all tests start?

For example, I may have to set up a docker container before all tests start. Is it possible to do this with mocha?

The before hook runs 1 time for every test file. This doesn't meet my needs.

Upvotes: 1

Views: 6755

Answers (3)

Izhaki
Izhaki

Reputation: 23586

Mocha 8 introduces the concept of root hook plugins. In your case, the relevant ones are beforeAll and afterAll, which will run once before/after all tests, so long you tests run in serial.

You can write:

exports.mochaHooks = {
  beforeAll(done) {
    // do something before all tests run
    done();
  },
};

And you'll have to add this file using the --require flag.

See docs for more info.

Upvotes: 2

Denis.Sabolotni
Denis.Sabolotni

Reputation: 1698

There is a very clean solution for this. Use --file as parameter in your mocha command. It works like a global hook for your tests.

xargs mocha -R spec --file <path-to-setup-file>

A setup file can look like this:

'use strict';
const mongoHelper = require('./mongoHelper.js');

console.log("[INFO]: Starting tests ...");
// connect to database

mongoHelper.connect()
.then(function(connection){
  console.log("[INFO]: Connected to database ...");
  console.log(connection);
})
.catch(function(err){
  console.error("[WARN]: Connection to database failed ...");
  console.log(err);
});

Unfortunately I have not found a way to use async/await in this setup files. So I think you may have to be conent with using "old" promise and callback code.

Upvotes: 0

Bence Gedai
Bence Gedai

Reputation: 1511

You can have 'root' level hooks, if you put them outside of any describe blocks. So you can put your relevant code in any files inside of the test folder.

before(function() {
  console.log('before any tests started');
});

See the docs: http://mochajs.org/#root-level-hooks

Upvotes: 5

Related Questions