I have an application that's currently using Mocha as its test runner, I've been exploring the native Node.js test runner but one stumbling block I've run into almost immediately is the question of how to start a long-running server that the tests require in order to function, in this case an MQTT broker, without blocking the actual tests from running afterwards.
My application is Express.js-based and connects to the MQTT broker at startup:
// app.js export default class App { constructor(port) { [...] this.connectToMqttBroker(); } } With Mocha this has worked quite happily using Aedes as the MQTT broker by running my "bootstrap" file before any of my other test files to start a temporary MQTT server:
// bootstrap.test.js // This is uncommented when using the native test runner of course // import { before } from "node:test"; import Aedes from 'aedes'; import { createServer } from 'net'; before(async function() { const aedes = new Aedes(); const server = createServer(aedes.handle); server.listen(1884, function() { console.log('MQTT server started and listening on port 1884'); }); }); The problem with the native test runner is that that server.listen() call seems to cause the test runner to pause at that point (which I guess makes certain amount of sense because it's now listening for connections) and none of the actual tests ever get run. I have the same problem if I use a pretest script in package.json that does essentially what's happening above but in a separate file before running the tests as well.
This is how I'm trying to run the tests with the Node test runner:
$ node --test src/test/bootstrap.test.js src/components/my-component/my-component.controller.test.js Adding --text-force-exit doesn't help because it's not getting to the point where the tests are even run, it pauses during the server.listen() call to start the MQTT broker.
Under Mocha it's a basically identical invocation but it works fine as long as I pass --exit or else it hangs after the tests have finished running:
./node_modules/.bin/mocha --exit src/test/bootstrap.test.js src/components/my-component/my-component.controller.test.js Is there some magical incantation I'm missing to get this working, or some alternative way of accomplishing what I'm trying to do here?
Many thanks!