p-queue 10 incompatibility with Jest + jsdom (`setMaxListeners` rejects jsdom's `EventTarget`)
Since 10.0.0, constructing a PQueue in a Jest test that uses the jsdom environment throws:
TypeError: The "eventTargets" argument must be an instance of EventEmitter or EventTarget. Received an instance of PQueue
at EventEmitter.setMaxListeners (node:events:321:17)
at new PQueue (node_modules/p-queue/dist/index.js:85:64)
I'm not sure this should be considered a bug, since it comes from how the test environment mixes Node and jsdom. I'm posting it partially in case others run into it, with a workaround and a possible fix below.
Reproduction
/** @jest-environment jsdom */
import PQueue from 'p-queue';
test('constructs', () => {
expect(() => new PQueue()).not.toThrow(); // fails
});
p-queue 10.0.0, Jest 30.5 with jest-environment-jsdom 30.5, Node 24.19. Works in plain Node and in browsers. Not tested under Vitest.
Cause
The constructor does:
globalThis.process?.getBuiltinModule?.('node:events')?.setMaxListeners(Infinity, this);
Under Jest's jsdom environment:
globalThis.processexists, because Jest installs a copy of Node's realprocess(includinggetBuiltinModule) in every environment, jsdom included. So this returns Node's realeventsmodule.EventTarget(whichPQueueextends) is jsdom's class, not Node's.
Node's setMaxListeners only accepts its own EventTarget instances, so it throws.
Possible fix within p-queue
Wrap the setMaxListeners call in a try/catch. The call only silences a warning, so skipping it when the target isn't one of Node's own EventTargets seems harmless.
Workaround
In a Jest setupFiles script, mark jsdom's EventTarget as one of Node's own:
// p-queue passes itself (a jsdom EventTarget) to Node's events.setMaxListeners,
// which rejects anything that lacks Node's EventTarget brand.
globalThis.EventTarget[Symbol.for('nodejs.event_target')] = true;
This relies on an undocumented Node internal (the symbol Node uses to recognize its own EventTargets).
Thank you.
PRs to this repo are limited to collaborators, so the fix is on a branch instead: https://github.com/MFA-G/p-queue/commit/f110c323a2fa620ab6bb87b3f53f60869affb4a7 (branch MFA-G:fix/jsdom-event-target).
It wraps the setMaxListeners() call in try/catch, as suggested above. It also adds a test that swaps globalThis.EventTarget for a non-Node class in a child process. That test fails on main with the same eventTargets error and passes with the fix. I also checked it by hand against real jsdom's EventTarget. npm test passes (281 tests). Feel free to cherry-pick it.
Not tested under Vitest.
Can confirm it also affects Vitest.
Is there a timeline for when a fix will be released?