Recently, while revisiting a Node.js repository I haven’t contributed to in ages, I encountered a new problem: the Mocha tests would hang instead of exiting. When I asked about the error, it seems it was recently introduced and nobody had pursued tracking down the root cause of the issue.
Conveniently, this issue was only happening locally, and our CI/CD build pipeline was not affected. Because of this, I also took the low road and decided to leave the sleuthing for another day.
The root cause is more than likely a stream that remained open. This really should be torn down as part of the
after code for whichever test was utilizing it. Ideally, the software engineer(s) should have identified this during development, but with the build pipeline not affected, it slipped through.
Engineering best practices aside, the issue itself is a minor one, really only affecting my ability to run the tests I was writing locally. I could certain hit
CTRL+C at the end of every test run, but that gets old fast.
Command-line arguments to the rescue
The solution? Fortunately,
mocha has a command-line argument you can pass in to tell it to force an exit after the test suite has run. This can be found by passing in
Armed with this command-line argument, running
mocha --exit would run my tests and exit as I would expect them to.