node/test/parallel/test-worker-message-port-infinite-message-loop.js
Jarred Sumner 9790315e15
test: ensure message event fires in worker message port test
Add assertion to verify that the MessagePort's message event is
actually emitted in test-worker-message-port-infinite-message-loop.js.
Previously, the test could pass even if the event was not fired.

PR-URL: https://github.com/nodejs/node/pull/59885
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
2025-10-01 12:46:47 +00:00

41 lines
1.2 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { MessageChannel } = require('worker_threads');
// Make sure that an infinite asynchronous .on('message')/postMessage loop
// does not lead to a stack overflow and does not starve the event loop.
// We schedule timeouts both from before the .on('message') handler and
// inside of it, which both should run.
const { port1, port2 } = new MessageChannel();
let count = 0;
port1.on('message', () => {
if (count === 0) {
setTimeout(common.mustCall(() => {
port1.close();
}), 0);
}
port2.postMessage(0);
assert(count++ < 10000, `hit ${count} loop iterations`);
});
port2.postMessage(0);
// This is part of the test -- the event loop should be available and not stall
// out due to the recursive .postMessage() calls.
setTimeout(common.mustCall(), 0);
// Assert that the 'message' handler was actually called.
//
// We do not want to assert a specific call count, so common.mustCall cannot be
// used in the port1.on('message' callback directly.
process.once(
'beforeExit',
common.mustCall(() => {
assert(count > 0, 'count should be greater than 0');
})
);