I have NodeJS project and tests via jest.
In quite a lot of places, the project calls some common function. Let’s call it myCommonModule.myCommonFunction
. That function cannot be executed during tests. It needs to be stubbed. I do that simply with sinon
like so
export const setUpStubForMyCommonFunction = () => {
const sandbox = sinon.createSandbox();
sandbox
.stub(myCommonModule, 'myCommonFunction')
.callsFake(async (organizationId) => {
// ...
});
});
};
and then call that function e.g in each test file where it’s needed, like
beforeAll(() => {
setUpStubForMyCommonFunction();
});
Works well. No big deal so far.
The problem starts with worker threads.
The project uses them roughly like so:
import { StaticPool } from 'node-worker-threads-pool';
class MyPool {
private pool: StaticPool;
constructor(options: StaticPoolOptions) {
this.pool = new StaticPool(options);
}
async exec(payload) {
await this.pool
.createExecutor()
.exec(payload);
}
}
const myPoolInstance = new MyPool({
task: path.resolve(__dirname, './my_worker_file.js'),
});
await myPoolInstance.exec(data)
The worker file looks like
import { parentPort } from 'worker_threads';
export const doSomething = async () => {
// ... Do a lot of stuff which should be tested
await myCommonModule.myCommonFunction()
};
parentPort!.on('message', async (data) => {
const result = await doSomething(data);
parentPort.postMessage(result);
});
The way it’s set-up right now, the stub works only in the main thread and not in the worker thread
Mocking the whole worker thingy is not an option. Testing what the worker actually does is the point of the test.
So, how to mock myCommonModule.myCommonFunction
in a way that even the worker file uses the mocked/stubbed version and not the original one?