Mocha tests hang after tests have finished

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 --help:

% npx mocha --help
mocha [spec..]

Run tests with Mocha

Commands
  mocha inspect [spec..]  Run tests with Mocha                         [default]
  mocha init <path>       create a client-side Mocha setup at <path>

Rules & Behavior
      --allow-uncaught       Allow uncaught errors to propagate        [boolean]
  -A, --async-only           Require all tests to use a callback (async) or
                             return a Promise                          [boolean]
  -b, --bail                 Abort ("bail") after first test failure   [boolean]
      --check-leaks          Check for global variable leaks           [boolean]
      --delay                Delay initial execution of root suite     [boolean]
      --dry-run              Report tests without executing them       [boolean]
      --exit                 Force Mocha to quit after tests complete  [boolean]
      
      ... even more arguments and resources
Zsh

Armed with this command-line argument, running mocha --exit would run my tests and exit as I would expect them to.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.