Skip to content

Commit 4c6b572

Browse files
smacpherson64gnapse
authored andcommitted
fix: #9 adjusted to-have-text-content for multi-level text (#61)
1 parent 40db857 commit 4c6b572

File tree

4 files changed

+36
-7
lines changed

4 files changed

+36
-7
lines changed

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
"dependencies": {
3535
"chalk": "^2.4.1",
3636
"css": "^2.2.3",
37-
"dom-testing-library": "^3.5.0",
3837
"jest-diff": "^22.4.3",
3938
"jest-matcher-utils": "^22.4.3",
4039
"pretty-format": "^23.0.1",

src/__tests__/to-have-text-content.js

+28
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,32 @@ describe('.toHaveTextContent', () => {
4545
normalizeWhitespace: false,
4646
})
4747
})
48+
49+
test('can handle multiple levels', () => {
50+
const {container} = render(`<span id="parent"><span>Step 1
51+
52+
of 4</span></span>`)
53+
54+
expect(container.querySelector('#parent')).toHaveTextContent('Step 1 of 4')
55+
})
56+
57+
test('can handle multiple levels with content spread across decendants', () => {
58+
const {container} = render(`
59+
<span id="parent">
60+
<span>Step</span>
61+
<span> 1</span>
62+
<span><span>of</span></span>
63+
64+
65+
4</span>
66+
</span>
67+
`)
68+
69+
expect(container.querySelector('#parent')).toHaveTextContent('Step 1 of 4')
70+
})
71+
72+
test('does not throw error with empty content', () => {
73+
const {container} = render(`<span></span>`)
74+
expect(container.querySelector('span')).toHaveTextContent('')
75+
})
4876
})

src/to-have-text-content.js

+3-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {matcherHint} from 'jest-matcher-utils'
2-
import {getNodeText} from 'dom-testing-library'
3-
import {checkHtmlElement, getMessage, matches} from './utils'
2+
import {checkHtmlElement, getMessage, matches, normalize} from './utils'
43

54
export function toHaveTextContent(
65
htmlElement,
@@ -10,10 +9,8 @@ export function toHaveTextContent(
109
checkHtmlElement(htmlElement, toHaveTextContent, this)
1110

1211
const textContent = options.normalizeWhitespace
13-
? getNodeText(htmlElement)
14-
.replace(/\s+/g, ' ')
15-
.trim()
16-
: getNodeText(htmlElement).replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces
12+
? normalize(htmlElement.textContent)
13+
: htmlElement.textContent.replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces
1714

1815
return {
1916
pass: matches(textContent, checkWith),

src/utils.js

+5
Original file line numberDiff line numberDiff line change
@@ -142,11 +142,16 @@ function deprecate(name, replacementText) {
142142
)
143143
}
144144

145+
function normalize(text) {
146+
return text.replace(/\s+/g, ' ').trim()
147+
}
148+
145149
export {
146150
checkDocumentKey,
147151
checkHtmlElement,
148152
checkValidCSS,
149153
deprecate,
150154
getMessage,
151155
matches,
156+
normalize,
152157
}

0 commit comments

Comments
 (0)