Skip to content

Commit 2a51345

Browse files
feat: add explicit error message for Promises passed to getWindowFromNode (#646)
* Added explicit error message for Promises passed to getWindowFromNode * Applied suggestion Closes #609
1 parent dbc1b3e commit 2a51345

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/__tests__/helpers.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,24 @@
1-
import {getDocument, checkContainerType} from '../helpers'
1+
import {getDocument, getWindowFromNode, checkContainerType} from '../helpers'
22

33
test('returns global document if exists', () => {
44
expect(getDocument()).toBe(document)
55
})
66

7+
describe('window retrieval throws when given something other than a node', () => {
8+
test('Promise as node', () => {
9+
expect(() =>
10+
getWindowFromNode(new Promise(jest.fn())),
11+
).toThrowErrorMatchingInlineSnapshot(
12+
`"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 do \`fireEvent.click(await screen.getBy...\`?"`,
13+
)
14+
})
15+
test('unknown as node', () => {
16+
expect(() => getWindowFromNode({})).toThrowErrorMatchingInlineSnapshot(
17+
`"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"`,
18+
)
19+
})
20+
})
21+
722
describe('query container validation throws when validation fails', () => {
823
test('undefined as container', () => {
924
expect(() =>

src/helpers.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ function getDocument() {
4747
return window.document
4848
}
4949
function getWindowFromNode(node) {
50-
// istanbul ignore next I'm not sure what could cause the final else so we'll leave it uncovered.
5150
if (node.defaultView) {
5251
// node is document
5352
return node.defaultView
@@ -57,8 +56,12 @@ function getWindowFromNode(node) {
5756
} else if (node.window) {
5857
// node is window
5958
return node.window
59+
} else if (node.then instanceof Function) {
60+
throw new Error(
61+
`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 do \`fireEvent.click(await screen.getBy...\`?`,
62+
)
6063
} else {
61-
// no idea...
64+
// The user passed something unusual to a calling function
6265
throw new Error(
6366
`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`,
6467
)

0 commit comments

Comments
 (0)