Skip to content

Commit

Permalink
fix: improve error message when no window found (#1089)
Browse files Browse the repository at this point in the history
* fix: improve error message when no screen found

* add test for HTMLElement with no window

* add a check for unavailable window

* fix typo
  • Loading branch information
MatanBobi committed Jan 25, 2022
1 parent d578c7e commit 7f5d421
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/__tests__/helpers.js
Expand Up @@ -25,9 +25,22 @@ describe('window retrieval throws when given something other than a node', () =>
`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...\`?`,
)
})
test('window is not available for node', () => {
const elem = document.createElement('div')
Object.defineProperty(elem.ownerDocument, 'defaultView', {
get: function get() {
return null
},
})

expect(() => getWindowFromNode(elem)).toThrowErrorMatchingInlineSnapshot(
`It looks like the window object is not available for the provided node.`,
)
})

test('unknown as node', () => {
expect(() => getWindowFromNode({})).toThrowErrorMatchingInlineSnapshot(
`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`,
`The given node is not an Element, the node type is: object.`,
)
})
})
Expand Down
6 changes: 5 additions & 1 deletion src/helpers.js
Expand Up @@ -33,6 +33,10 @@ function getWindowFromNode(node) {
} else if (node.window) {
// node is window
return node.window
} else if (node.ownerDocument && node.ownerDocument.defaultView === null) {
throw new Error(
`It looks like the window object is not available for the provided node.`,
)
} else if (node.then instanceof Function) {
throw new Error(
`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...\`?`,
Expand All @@ -51,7 +55,7 @@ function getWindowFromNode(node) {
} else {
// The user passed something unusual to a calling function
throw new Error(
`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`,
`The given node is not an Element, the node type is: ${typeof node}.`,
)
}
}
Expand Down

0 comments on commit 7f5d421

Please sign in to comment.