First, I would definitely use mocha.opts
so that you don't have to include the options you want every time. As pointed out, one option is to use --grep
, but I am not a huge fan of that personally. It required you name everything in an overly simplistic way. If the before
hook is NOT async you can use --require
in your mocha.opts
. e.g.
#mocha.opts
--recursive
--require test/helpers.js
It sounds like this wouldn't work for you because you want global after
hook as well. What I have done is I just call the full test suite every time, but if I am in the middle of deving and only want to test one suite, or even one specific test, I use the exclusivity feature, only
https://mochajs.org/#exclusive-tests. You can make it it.only('...
or describe.only('...
If you do this it looks through all tests and sets up exactly like your full test harness would, but then only executes the test or suite you have specified.
Now you can include those global hooks no problem. @Louis mentions that your helpers.js
are loading in the proper order only coincidently. That is not true. If you place any hooks outside of a describe
block, it automatically becomes a global hook. This can be accomplished by either putting it in its own file
// helpers.js
before(function() { console.log('testing...'); });
or within a test file
// some.spec.js
before(function() { console.log('testing...'); });
describe('Something', function() {
it('will be tested', function() {
...
});
});
Obviously, I think putting it in its own file is cleaner. (I called it hooks.js
). Point is, this is not a result of the order in which files were loaded.
Just one gotcha that might be obvious to other but I struggled with briefly -- hooks not placed in a describe
block are ALL global. They are not directory specific. So if you copy helpers.js
into a sub-directory of tests, the before
and after
hook will now fire twice. Also, if you place a beforeEach
hook in there, it will fire before every single test, not just those tests in that directory.
Anyway, I know this post is a bit old, but hopefully this will help others having similar issues.