Skip to content

Commit ccc12c3

Browse files
committed
fix(cdk/testing): errors in harnesses when using Vitest (#32399)
Fixes that we were hitting an error due to the DOM implementation that Vitest is using when constructing events. (cherry picked from commit d41d397)
1 parent a68964a commit ccc12c3

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/cdk/testing/testbed/fake-events/event-objects.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export function createMouseEvent(
3535
bubbles: true,
3636
cancelable: true,
3737
composed: true, // Required for shadow DOM events.
38-
view: window,
38+
view: getEventView(),
3939
detail: 1,
4040
relatedTarget: null,
4141
screenX,
@@ -85,7 +85,7 @@ export function createPointerEvent(
8585
bubbles: true,
8686
cancelable: true,
8787
composed: true, // Required for shadow DOM events.
88-
view: window,
88+
view: getEventView(),
8989
clientX,
9090
clientY,
9191
...options,
@@ -139,7 +139,7 @@ export function createKeyboardEvent(
139139
bubbles: true,
140140
cancelable: true,
141141
composed: true, // Required for shadow DOM events.
142-
view: window,
142+
view: getEventView(),
143143
keyCode,
144144
key,
145145
shiftKey: modifiers.shift,
@@ -165,3 +165,13 @@ export function createFakeEvent(type: string, bubbles = false, cancelable = true
165165
function defineReadonlyEventProperty(event: Event, propertyName: string, value: any) {
166166
Object.defineProperty(event, propertyName, {get: () => value, configurable: true});
167167
}
168+
169+
/** Gets the `view` that should be passed to synthetically-created DOM events */
170+
function getEventView(): Window | undefined {
171+
// Passing `window` as the `view` on for events when the environment is using jsdom
172+
// ends up throwing `member view is not of type Window` (see #32389). Leave it as
173+
// `undefined` for such cases.
174+
return typeof window !== 'undefined' && window && !(window as Window & {jsdom?: unknown}).jsdom
175+
? window
176+
: undefined;
177+
}

0 commit comments

Comments
 (0)