Skip to content

Commit caffc56

Browse files
author
Kent C. Dodds
committed
fix(fireEvent): accept window for fireEvent shortcuts
Ref #165
1 parent 0af4914 commit caffc56

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/__tests__/events.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,14 @@ test('fires events on Window', () => {
186186
window.removeEventListener('message', messageSpy)
187187
})
188188

189+
test('fires shortcut events on Window', () => {
190+
const clickSpy = jest.fn()
191+
window.addEventListener('click', clickSpy)
192+
fireEvent.click(window)
193+
expect(clickSpy).toHaveBeenCalledTimes(1)
194+
window.removeEventListener('message', clickSpy)
195+
})
196+
189197
test('fires events on Document', () => {
190198
const keyDownSpy = jest.fn()
191199
document.addEventListener('keydown', keyDownSpy)

src/events.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,14 +329,32 @@ Object.keys(eventMap).forEach(key => {
329329
value: files,
330330
})
331331
}
332-
// if the node does not have an owner document, then it probably _is_ the owner document
333-
const window = (node.ownerDocument || node).defaultView
332+
const window = getWindowFromNode(node)
334333
const EventConstructor = window[EventType] || window.Event
335334
const event = new EventConstructor(eventName, eventInit)
336335
return fireEvent(node, event)
337336
}
338337
})
339338

339+
function getWindowFromNode(node) {
340+
// istanbul ignore next I'm not sure what could cause the final else so we'll leave it uncovered.
341+
if (node.defaultView) {
342+
// node is document
343+
return node.defaultView
344+
} else if (node.ownerDocument) {
345+
// node is a DOM node
346+
return node.ownerDocument.defaultView
347+
} else if (node.window) {
348+
// node is window
349+
return node.window
350+
} else {
351+
// no idea...
352+
throw new Error(
353+
`Unable to find the "window" object for the given node. fireEvent currently supports firing events on DOM nodes, document, and window. Please file an issue with the code that's causing you to see this error: https://github.com/kentcdodds/dom-testing-library/issues/new`,
354+
)
355+
}
356+
}
357+
340358
// function written after some investigation here:
341359
// https://github.com/facebook/react/issues/10135#issuecomment-401496776
342360
function setNativeValue(element, value) {

0 commit comments

Comments
 (0)