Imagine you have Mocha unit tests, like these ones
1 | it('test a', () => {}) |
You can run these tests by installing Mocha
1 | npm i mocha |
and then running the command
1 | npx mocha ./spec.js |
Beautiful, but what if we want to change the list of collected tests before running them? What if we want to filter tests and maybe run only some of them? We could use --grep
command option, for example we could run just the "test b".
1 | npx mocha --grep "test b" ./spec.js |
I want more. I want to run previously failed tests first. Or run the slowest tests first, or randomize the test order to find the dependencies among tests. Previously I have written tools for this, like rocha and locha but those tools have a limitation - they wrap around Mocha, rather than modifying its behavior. They do not reuse Mocha's CLI module, which means as Mocha gets more features, those other tools fall behind.
I would like to plug right into Mocha's internals and add a new hook that runs after Mocha has collected the tests, but before they start running. Here is how to do this - all using the most powerful and underused feature of Node.js - its --require
option. Mocha actually looks for --require
CLI option and loads those modules for us. So how can we take advantage of loading our code to change Mocha's behavior?
First, find in Mocha's code the place where collected tests are being executed. That's easy - it is the code inside the file lib/runner.js
that has (surprise, surprise) prototype method run
1 | /** |
Great, and this is an asynchronous function too, so we can modify the list of tests in whatever way we want. We can load files, make HTTP calls - even ask the user which tests to run. All we need is to overwrite this method, prefixing it with our code. Start a new local file, let's call it reorder.js
. Here is how to reverse the order of tests in the root suite.
1 | const Runner = require('mocha/lib/runner') |
Let's run Mocha and require this script - it will reverse the order of tests
1 | npx mocha --require ./reorder ./spec.js |
Because we have the callback function, we can make our logic asynchronous. Here is reversing the test order after 1 second delay
1 | const Runner = require('mocha/lib/runner') |
Runs the same way, except for 1 second pause before running the tests.
We can even ask the user what test to run. Here is a CLI script that asks the user using the enquirer library.
1 | const { Select } = require('enquirer') |
And here is the hook in action
Just remember - in the real world situation, you need to look through each suite of tests to modify them, and probably consider the interplay between filtering tests and exclusive / skipped tests. For example, if there is an exclusive test with it.only
, you probably do not want to run all the tests, right?!