How can I make Mocha load a helper.js file that defines global hooks or utilities?

Mocha does not have any notion of a special file named helper.js that it would load before other files.

What you are trying to do works when you run mocha --recursive because of the order in which Mocha happens to load your files. Because helper.js is one level higher than the other files, it is loaded first. When you specify an individual file to Mocha, then Mocha just loads this file and, as you discovered, your helper.js file is not loaded at all.

So what you want to do is load a file such that it will set top level (“global”) hooks (e.g. before, after, etc.). Options:

  1. You could use Mocha programmatically and feed it the files in the order you want.

  2. You could force yourself to always specify your helper file on the command line first before you list any other file. (I would not do this, but it is possible.)

  3. Another option would be to organize your suite like I’ve detailed in this answer. Basically, you have one “top level” file that loads the rest of the suite into it. With this method you’d lose the ability of running Mocha on individual files, but you could use --grep to select what is being run.

You cannot use the -r option. It loads a module before running the suite but, unfortunately, the loaded module does not have access to any of the testing interface that Mocha makes available to your tests so it cannot set hooks.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)