Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing WorkerThreads with ts-mocha. #68

Open
akirilyuk opened this issue Nov 3, 2021 · 1 comment
Open

Testing WorkerThreads with ts-mocha. #68

akirilyuk opened this issue Nov 3, 2021 · 1 comment

Comments

@akirilyuk
Copy link

akirilyuk commented Nov 3, 2021

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?

@akirilyuk
Copy link
Author

akirilyuk commented Nov 3, 2021

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
	});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant