ts-mocha
ts-mocha copied to clipboard
Testing WorkerThreads with ts-mocha.
Hi, when trying to create a test that tests the behavior of WorkerThreads, it fails to start the application with this error message, failing to parse my workerScript.ts:
import { parentPort } from "worker_threads";
^^^^^^
SyntaxError: Cannot use import statement outside a module
The application itself can be started with and is working via node -r ts-node/register/transpile-only
Is there any option to test WorkerThreads behaviour via ts-mocha at all?
Until this issue is fixed, I have found a workaround so I am still able to test code which relies on WorkerThreads module: Simply create a loader file as described below. You would then need to load the loader file via a Worker and this will then load the actual script and register ts-node if running in TS.
// this is a loader module to load the actual ts worker file
const path = require('path');
const {parentPort} = require("worker_threads");
try {
const fileName = __filename.slice(__dirname.length + 1);
const fileExtension = fileName.slice(fileName.length - 2);
// only register ts-node if we are inside a .ts file
if (fileExtension == "ts") {
require('ts-node').register({
project: __dirname.concat(process.env.NODE_ENV === "production" ? "../../../../tsconfig.production.json" : "../../../../tsconfig.json"),
transpileOnly: true,
});
}
require(path.resolve(__dirname, `./yourActualWorkerTask.${fileExtension}`));
} catch (error) {
parentPort.postMessage({
result: null,
error
});
}