Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: check for any Node in toHaveTextContent #307

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/__tests__/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ describe('.toHaveTextContent', () => {
expect(queryByTestId('count-value')).not.toHaveTextContent('21')
})

test('handles non-element nodes', () => {
const {container} = render(`<span>example</span>`)

expect(container.querySelector('span').firstChild).toHaveTextContent(
'example',
)
})

test('handles negative test cases', () => {
const {queryByTestId} = render(`<span data-testid="count-value">2</span>`)

Expand Down
8 changes: 6 additions & 2 deletions src/to-have-text-content.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import {checkHtmlElement, getMessage, matches, normalize} from './utils'
import {getMessage, HtmlElementTypeError, matches, normalize} from './utils'

export function toHaveTextContent(
htmlElement,
checkWith,
options = {normalizeWhitespace: true},
) {
checkHtmlElement(htmlElement, toHaveTextContent, this)
const window = htmlElement.ownerDocument.defaultView
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be a check prior to this line. Otherwise this line can throw when receiving something that does not even have a ownerDocument property. Or if the obtained window value is not a window object and does not have a window.Node thing in it.


if (!(htmlElement instanceof window.Node)) {
throw new HtmlElementTypeError(toHaveTextContent, this)
}

const textContent = options.normalizeWhitespace
? normalize(htmlElement.textContent)
Expand Down