Skip to content

Commit 792c5b7

Browse files
DylanPierceyKent C. Dodds
authored and
Kent C. Dodds
committed
fix: support jsdom detached fragments (#288)
* fix: support jsdom detached fragments * docs: link to mdn for TEXT_NODE constant
1 parent c4b4eff commit 792c5b7

File tree

3 files changed

+35
-7
lines changed

3 files changed

+35
-7
lines changed

src/__node_tests__/index.js

+29
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,32 @@ test('works without a global dom', async () => {
4747
const data = JSON.parse(submittedDataPre.textContent)
4848
expect(data).toEqual(fakeUser)
4949
})
50+
51+
test('works without a browser context on a dom node (JSDOM Fragment)', () => {
52+
const container = JSDOM.fragment(`
53+
<html>
54+
<body>
55+
<form id="login-form">
56+
<label for="username">Username</label>
57+
<input id="username" />
58+
<label for="password">Password</label>
59+
<input id="password" type="password" />
60+
<button type="submit">Submit</button>
61+
<div id="data-container"></div>
62+
</form>
63+
</body>
64+
</html>
65+
`)
66+
67+
expect(dtl.getByLabelText(container, /username/i)).toMatchInlineSnapshot(`
68+
<input
69+
id="username"
70+
/>
71+
`)
72+
expect(dtl.getByLabelText(container, /password/i)).toMatchInlineSnapshot(`
73+
<input
74+
id="password"
75+
type="password"
76+
/>
77+
`)
78+
})

src/events.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ function getWindowFromNode(node) {
344344
if (node.defaultView) {
345345
// node is document
346346
return node.defaultView
347-
} else if (node.ownerDocument) {
347+
} else if (node.ownerDocument && node.ownerDocument.defaultView) {
348348
// node is a DOM node
349349
return node.ownerDocument.defaultView
350350
} else if (node.window) {

src/get-node-text.js

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1-
function getNodeText(node) {
2-
const window = node.ownerDocument.defaultView
1+
// Constant node.nodeType for text nodes, see:
2+
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType#Node_type_constants
3+
const TEXT_NODE = 3
34

5+
function getNodeText(node) {
46
if (node.matches('input[type=submit], input[type=button]')) {
57
return node.value
68
}
79

810
return Array.from(node.childNodes)
9-
.filter(
10-
child =>
11-
child.nodeType === window.Node.TEXT_NODE && Boolean(child.textContent),
12-
)
11+
.filter(child => child.nodeType === TEXT_NODE && Boolean(child.textContent))
1312
.map(c => c.textContent)
1413
.join('')
1514
}

0 commit comments

Comments
 (0)