Skip to content

Commit 748ee2d

Browse files
authored
test: avoid missing worker exit events (#65)
## Motivation The worker lifecycle test waited for the worker message before registering its exit listener. Node can drain a queued message and emit `exit` in the same turn, causing the test to miss the exit event and time out intermittently in CI. ## Description - Register the worker `message` and `exit` listeners before yielding. - Await both events together with `node:events` `once()`, which also propagates worker errors. - Assert a successful worker exit and check the restored refcount without an arbitrary delay. Validated by running the worker lifecycle suite 50 consecutive times.
1 parent fff76f3 commit 748ee2d

1 file changed

Lines changed: 9 additions & 15 deletions

File tree

‎examples/js_dsl/mod.test.ts‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,7 @@ describe("class return interop", () => {
718718

719719
describe("module lifecycle - worker threads", () => {
720720
it("worker thread increments refcount and cleanup decrements it", async () => {
721+
const { once } = await import("node:events");
721722
const { Worker } = await import("node:worker_threads");
722723
const { resolve } = await import("node:path");
723724
const { fileURLToPath } = await import("node:url");
@@ -738,22 +739,15 @@ describe("module lifecycle - worker threads", () => {
738739
{ eval: true, workerData: { nativePath } },
739740
);
740741

741-
// Worker should see an incremented refcount
742-
const workerRefcount = await new Promise((resolve) => {
743-
worker.on("message", (msg) => {
744-
resolve(msg.refcount);
745-
});
746-
});
747-
expect(workerRefcount).toBeGreaterThan(refcountBefore);
748-
749-
// Wait for worker to exit (triggers cleanup hook)
750-
await new Promise((resolve) => {
751-
worker.on("exit", () => resolve(undefined));
752-
});
742+
// Node may drain the queued message and emit exit in the same turn.
743+
// Register both listeners before yielding so neither event can be missed.
744+
const [[message], [exitCode]] = await Promise.all([
745+
once(worker, "message"),
746+
once(worker, "exit"),
747+
]);
753748

754-
// After worker exits, refcount should be back to what it was
755-
// Give a small delay for cleanup hook to fire
756-
await new Promise((resolve) => setTimeout(resolve, 100));
749+
expect(message.refcount).toBeGreaterThan(refcountBefore);
750+
expect(exitCode).toEqual(0);
757751
expect(mod.getEnvRefcount()).toEqual(refcountBefore);
758752
});
759753
});

0 commit comments

Comments
 (0)