Share a function between threads in pool #6527
-
Dear community, I need your help in figuring out how to share a function among the tests running in different threads. I have a generator* function, that returns different ports each time being called, and I multiple files/tests should use it to spin a HTTP server on that unique port. It works fine in CI, where is a single thread, or with setting Currently, having multiple threads, each thread gets a copy of that generator* function, so that it leads to the same ports returned and tests are failing. I tried const disposer = (function* () {
let port = 8010;
while (true) yield port++;
})();
export const givePort = (): number => disposer.next().value; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
So far I found a workaround to utilize the const disposer = (function* () {
let port = 8e3 + 1e2 * Number(process.env.VITEST_POOL_ID);
while (true) yield port++;
})();
export const givePort = (): number => disposer.next().value; |
Beta Was this translation helpful? Give feedback.
VITEST_POOL_ID
will be unique on each test runner thread so you can use that to derive unique numbers. Other solutions could be to create small HTTP or websocket server where you could fetch the port number. Or read it from file system - but that could run into race conditions when there's no locking system used.Internally Vitest uses
node:worker_thread
's communication channel, but we don't expose it to users in any way. I've seen requests like this before, so I'm starting to think if we should provide a way for users to call main thread from test runner threads. 🤔