Skip to content

Commit 7f5d421

Browse files
authored
fix: improve error message when no window found (#1089)
* fix: improve error message when no screen found * add test for HTMLElement with no window * add a check for unavailable window * fix typo
1 parent d578c7e commit 7f5d421

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/__tests__/helpers.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,22 @@ describe('window retrieval throws when given something other than a node', () =>
2525
`It looks like you passed an Array instead of a DOM node. Did you do something like \`fireEvent.click(screen.getAllBy...\` when you meant to use a \`getBy\` query \`fireEvent.click(screen.getBy...\`?`,
2626
)
2727
})
28+
test('window is not available for node', () => {
29+
const elem = document.createElement('div')
30+
Object.defineProperty(elem.ownerDocument, 'defaultView', {
31+
get: function get() {
32+
return null
33+
},
34+
})
35+
36+
expect(() => getWindowFromNode(elem)).toThrowErrorMatchingInlineSnapshot(
37+
`It looks like the window object is not available for the provided node.`,
38+
)
39+
})
40+
2841
test('unknown as node', () => {
2942
expect(() => getWindowFromNode({})).toThrowErrorMatchingInlineSnapshot(
30-
`Unable to find the "window" object for the given node. Please file an issue with the code that's causing you to see this error: https://github.com/testing-library/dom-testing-library/issues/new`,
43+
`The given node is not an Element, the node type is: object.`,
3144
)
3245
})
3346
})

src/helpers.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ function getWindowFromNode(node) {
3333
} else if (node.window) {
3434
// node is window
3535
return node.window
36+
} else if (node.ownerDocument && node.ownerDocument.defaultView === null) {
37+
throw new Error(
38+
`It looks like the window object is not available for the provided node.`,
39+
)
3640
} else if (node.then instanceof Function) {
3741
throw new Error(
3842
`It looks like you passed a Promise object instead of a DOM node. Did you do something like \`fireEvent.click(screen.findBy...\` when you meant to use a \`getBy\` query \`fireEvent.click(screen.getBy...\`, or await the findBy query \`fireEvent.click(await screen.findBy...\`?`,
@@ -51,7 +55,7 @@ function getWindowFromNode(node) {
5155
} else {
5256
// The user passed something unusual to a calling function
5357
throw new Error(
54-
`Unable to find the "window" object for the given node. Please file an issue with the code that's causing you to see this error: https://github.com/testing-library/dom-testing-library/issues/new`,
58+
`The given node is not an Element, the node type is: ${typeof node}.`,
5559
)
5660
}
5761
}

0 commit comments

Comments
 (0)