Global `before` and `beforeEach` for mocha?

In the root of the test folder, create a global test helper test/helper.js which has your before and beforeEach

// globals
global.assert = require('assert');

// setup
before();
beforeEach();

// teardown
after();
afterEach();

from the mocha documentation…

ROOT-LEVEL HOOKS

You may also pick any file and add “root”-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the “root suite

All regular describe()-suites are first collected and only then run, this kinda guarantees this being called first.

'use strict'
let run = false

beforeEach(function() {
    if ( run === true ) return
    console.log('GLOBAL ############################')
    run = true
});

Remove the run-flag, if you want to see it run each time, before every test.

I named this file test/_beforeAll.test.js. It has no need to be imported/required anywhere, but the .test. (resp. .spec.) in the filename is important, so that your testrunner picks it up…


bonus track 8-): using mocha.opts \o/

If there's stuff, you truly only want to set up once before running your tests (regardless which ones...), mocha.opts is a surprisingly elegant option! – Just add a require to your file (yes, even if it contributes little to mocha, but rather to your test setup). It will run reliably once before:

enter image description here

( in this example I detect, if a single test or many tests are about to run. In the former case I output every log.info(), while on a full run I reduce verbosity to error+warn... )

Update:

If someone knows a way, to access some basic properties of the mocha suite that is about to be run in once.js, I would love to know and add here. (i.e. my suiteMode-detection is lousy, if there was another way to detect, how many tests are to be run…)