Skip to content

Commit cdc8a06

Browse files
kandrosgnapse
authored andcommitted
fix: toHaveTextContent("") causing false positive (#138)
* throw when matching against empty string sugget toBeEmpty fix #104 * allow empty content to match empty string
1 parent bcc7339 commit cdc8a06

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,13 @@ describe('.toHaveTextContent', () => {
8282
'sensitive text',
8383
)
8484
})
85+
86+
test('when matching with empty string and element with content suggest using toBeEmpty instead', () => {
87+
// https://github.com/testing-library/jest-dom/issues/104
88+
const {container} = render('<span>not empty</span>')
89+
90+
expect(() =>
91+
expect(container.querySelector('span')).toHaveTextContent(''),
92+
).toThrowError(/toBeEmpty()/)
93+
})
8594
})

src/to-have-text-content.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@ export function toHaveTextContent(
1212
? normalize(htmlElement.textContent)
1313
: htmlElement.textContent.replace(/\u00a0/g, ' ') // Replace &nbsp; with normal spaces
1414

15+
const checkingWithEmptyString = textContent !== '' && checkWith === ''
16+
1517
return {
16-
pass: matches(textContent, checkWith),
18+
pass: !checkingWithEmptyString && matches(textContent, checkWith),
1719
message: () => {
1820
const to = this.isNot ? 'not to' : 'to'
1921
return getMessage(
@@ -22,7 +24,9 @@ export function toHaveTextContent(
2224
'element',
2325
'',
2426
),
25-
`Expected element ${to} have text content`,
27+
checkingWithEmptyString
28+
? `Checking with empty string will always match, use .toBeEmpty() instead`
29+
: `Expected element ${to} have text content`,
2630
checkWith,
2731
'Received',
2832
textContent,

0 commit comments

Comments
 (0)