Skip to content

Commit

Permalink
fix: #9 adjusted to-have-text-content for multi-level text (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
smacpherson64 authored and gnapse committed Oct 4, 2018
1 parent 40db857 commit 4c6b572
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 7 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"dependencies": {
"chalk": "^2.4.1",
"css": "^2.2.3",
"dom-testing-library": "^3.5.0",
"jest-diff": "^22.4.3",
"jest-matcher-utils": "^22.4.3",
"pretty-format": "^23.0.1",
Expand Down
28 changes: 28 additions & 0 deletions src/__tests__/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,32 @@ describe('.toHaveTextContent', () => {
normalizeWhitespace: false,
})
})

test('can handle multiple levels', () => {
const {container} = render(`<span id="parent"><span>Step 1
of 4</span></span>`)

expect(container.querySelector('#parent')).toHaveTextContent('Step 1 of 4')
})

test('can handle multiple levels with content spread across decendants', () => {
const {container} = render(`
<span id="parent">
<span>Step</span>
<span> 1</span>
<span><span>of</span></span>
4</span>
</span>
`)

expect(container.querySelector('#parent')).toHaveTextContent('Step 1 of 4')
})

test('does not throw error with empty content', () => {
const {container} = render(`<span></span>`)
expect(container.querySelector('span')).toHaveTextContent('')
})
})
9 changes: 3 additions & 6 deletions src/to-have-text-content.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {matcherHint} from 'jest-matcher-utils'
import {getNodeText} from 'dom-testing-library'
import {checkHtmlElement, getMessage, matches} from './utils'
import {checkHtmlElement, getMessage, matches, normalize} from './utils'

export function toHaveTextContent(
htmlElement,
Expand All @@ -10,10 +9,8 @@ export function toHaveTextContent(
checkHtmlElement(htmlElement, toHaveTextContent, this)

const textContent = options.normalizeWhitespace
? getNodeText(htmlElement)
.replace(/\s+/g, ' ')
.trim()
: getNodeText(htmlElement).replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces
? normalize(htmlElement.textContent)
: htmlElement.textContent.replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces

return {
pass: matches(textContent, checkWith),
Expand Down
5 changes: 5 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,11 +142,16 @@ function deprecate(name, replacementText) {
)
}

function normalize(text) {
return text.replace(/\s+/g, ' ').trim()
}

export {
checkDocumentKey,
checkHtmlElement,
checkValidCSS,
deprecate,
getMessage,
matches,
normalize,
}

0 comments on commit 4c6b572

Please sign in to comment.