node.jstestingjestjsworker-threadnode-worker-threads

How to test a worker thread in NodeJS?


I have a node script that uses a worker thread. I want to test it with Jest. The file is called, but the code is never executed.

Here is the function that calls the worker:

// index.ts 
function foo(){
  const worker = new Worker(path.resolve(__dirname, "./worker.ts"));
  worker.on("message", (e) => {
   // do stuff
  });
}

Here is the worker:

// worker.ts
const { parentPort } = require("worker_threads");
const { doStuff } = require("./index");

parentPort?.on("message", async (e) => {
    const data = await doStuff(e);
    parentPort?.postMessage({ data });
 }
);

What am I doing wrong? I've tried to mock a Worker in Jest, but it's not called. I've also tried to compile worker.ts to a worker.js file before using it.


Solution

  • The fix was to compile worker.ts to a .cjs file, because the worker was importing code from other typescript files.