Running a set of actions before every test-file in mocha

There are three basic levels of factoring out common functionality for mocha tests. If you want to load in some fixtures once for a bunch of tests (and you've written each test to be independent), use the before function to load the fixtures at the top of the file. You can also use beforeEach function if you need the fixtures re-initialized each time.

The second option (which is related), is to pull out common functionality into a separate file or set of files and require that file.

Finally, note that mocha has a root level hook:

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").

We use that to start an Express server once (and we use an environment variable so that it runs on a different port than our development server):

before(function () {
  process.env.NODE_ENV = 'test';
  require('../../app.js');
});

(We don't need a done() here because require is synchronous.) This was, the server is started exactly once, no matter how many different test files include this root-level before function.

The advantage of splitting things up in this way is that we can run npm test which runs all tests, or run mocha on any specific file or any specific folder, or any specific test or set of tests (using it.only and describe.only) and all of the prerequisites for the selected tests will run.


Why not mocha -r <module> or even using mocha.opts?

Have your common file in, say, init.js and then run

mocha -r `./init`

Which will cause mocha to run and load ./init.js before loading any of the mocha test files.

You could also put it in mocha.opts inside your tests directory, and have its contents be

--require ./init