dev-test: JSDOM's Event and CustomEvent win over Node's in the browser env

Globals were only set where Node had none, and Node defines Event and
CustomEvent itself. Code running in the browser env therefore built
Node events, which a JSDOM node refuses: react-tooltip's
window.dispatchEvent(new CustomEvent(...)) threw "parameter 1 is not of
type 'Event'". In the browser env these two now come from JSDOM, as they
do under jest-environment-jsdom.
This commit is contained in:
Satoshi Qazi Muhammed committed 2026-10-10 08:53:49 +04:00
1 parent 1ba9b3e57f
commit 0cd4f12cfb
3 files changed
+21 -2

No files matched your search

+5
View File
@@ -23,4 +23,9 @@ describe('browser', () => {
it('contains HTML*Element', () => {
expect(typeof all.HTMLElement).toBe('function');
});
it('dispatches the global CustomEvent and Event on window', () => {
expect(() => window.dispatchEvent(new CustomEvent('custom', { detail: 1 }))).not.toThrow();
expect(() => window.dispatchEvent(new Event('plain'))).not.toThrow();
});
});
+10
View File
@@ -3,6 +3,13 @@
import { JSDOM } from 'jsdom';
/**
* Constructors that Node defines as well. A DOM node only accepts an event
* created in its own realm, so in the browser environment the JSDOM ones
* replace Node's, as they do under jest-environment-jsdom.
*/
export const BROWSER_OVERRIDES: readonly string[] = ['CustomEvent', 'Event'];
/**
* Export a very basic JSDom environment - this is just enough so we have
* @testing-environment/react tests passing in this repo
@@ -15,6 +22,9 @@ export function browser () {
const { window } = new JSDOM('', { url: 'http://localhost' });
return {
// Event constructors, see BROWSER_OVERRIDES
CustomEvent: window.CustomEvent,
Event: window.Event,
// All HTML Elements that are defined on the JSDOM window object.
// (we copied as-is from the types definition). We cannot get this
// via Object.keys(window).filter(...) so we have to specify explicitly
+6 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2026 @pezkuwi/dev-test authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { browser } from './browser.js';
import { browser, BROWSER_OVERRIDES } from './browser.js';
import { expect } from './expect.js';
import { jest } from './jest.js';
import { lifecycle } from './lifecycle.js';
@@ -15,7 +15,11 @@ export function exposeEnv (isBrowser: boolean): void {
env && Object
.entries(env())
.forEach(([key, fn]) => {
globalThis[key as 'undefined'] ??= fn;
if (isBrowser && BROWSER_OVERRIDES.includes(key)) {
(globalThis as Record<string, unknown>)[key] = fn;
} else {
globalThis[key as 'undefined'] ??= fn;
}
});
});
}