Relationship between main thread and worker threads in Node.js: Context isolation and message exchange

I have tried implementing a test in my NodeJS service using Jest.
I’ve leveraged the auto mocks feature from Jest when mocking node_modules.

Since my application uses workers, I’ve noticed that the context of the workers knows nothing about the Jest environment and with it nothing about the mocked modules. Hence, my first question was:

  1. Is there a way to share mocks from the main thread with workers?

That question sparked my interest further, as I wanted to understand better how the workers are created and how the main thread and workers in NodeJS bound together. I’ve read a couple of articles, but some things are still not clear for me.

  1. How does the exchange of messages happen between the main thread and workers?
  2. If I understood correctly, main thread and the workers are part of the same process and share the memory. Why do they have different context?

I’ve seen this thread, and from there I drew the conclusion that context sharing won’t be possible.

There is a possibility to share the mocks via worker_data parameter when creating a worker thread. This is not a solution to my problem, but it looks to me that Jest and its mocks just won’t work with the worker threads the way they work in the main thread.

const worker = new Worker('./worker.js', { workerData: mockData });

worker.js:

const { workerData } = require('worker_threads'); 
const { produce, startConsumer } = workerData;

So I believe this answers the first question.

It still leaves me with a gap on the relationship between main and worker threads that I’ve asked about in points 2. and 3.