Skip to content

Commit

Permalink
fix: toHaveTextContent("") causing false positive (#138)
Browse files Browse the repository at this point in the history
* throw when matching against empty string sugget toBeEmpty

fix #104

* allow empty content to match empty string
  • Loading branch information
kandros authored and gnapse committed Oct 7, 2019
1 parent bcc7339 commit cdc8a06
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 9 additions & 0 deletions src/__tests__/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,13 @@ describe('.toHaveTextContent', () => {
'sensitive text',
)
})

test('when matching with empty string and element with content suggest using toBeEmpty instead', () => {
// https://github.com/testing-library/jest-dom/issues/104
const {container} = render('<span>not empty</span>')

expect(() =>
expect(container.querySelector('span')).toHaveTextContent(''),
).toThrowError(/toBeEmpty()/)
})
})
8 changes: 6 additions & 2 deletions src/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ export function toHaveTextContent(
? normalize(htmlElement.textContent)
: htmlElement.textContent.replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces

const checkingWithEmptyString = textContent !== '' && checkWith === ''

return {
pass: matches(textContent, checkWith),
pass: !checkingWithEmptyString && matches(textContent, checkWith),
message: () => {
const to = this.isNot ? 'not to' : 'to'
return getMessage(
Expand All @@ -22,7 +24,9 @@ export function toHaveTextContent(
'element',
'',
),
`Expected element ${to} have text content`,
checkingWithEmptyString
? `Checking with empty string will always match, use .toBeEmpty() instead`
: `Expected element ${to} have text content`,
checkWith,
'Received',
textContent,
Expand Down

0 comments on commit cdc8a06

Please sign in to comment.