// this is an out of date version, use the one below
const getNodeText = node => {
if (['string', 'number'].includes(typeof node)) return node
if (node instanceof Array) return node.map(getNodeText).join('')
if (typeof node === 'object' && node) return getNodeText(node.props.children)
}
https://codesandbox.io/s/react-getnodetext-h21ss
// in the screenshot above
const heading = <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
return (
<div>
{heading}
<pre ref={printInnerHTML}/>
<pre>{getNodeText(heading)}</pre>
</div>
)
TypeScript update
const getNodeText = (node: React.ReactNode): string => {
if (node == null) return ''
switch (typeof node) {
case 'string':
case 'number':
return node.toString()
case 'boolean':
return ''
case 'object': {
if (node instanceof Array)
return node.map(getNodeText).join('')
if ('props' in node)
return getNodeText(node.props.children)
} // eslint-ignore-line no-fallthrough
default:
console.warn('Unresolved `node` of type:', typeof node, node)
return ''
}
}
react-testing-library
might be the answer to this and many other questions you may have concerning frontend code tests. Don't test for internal details, test for what a user actually sees. – Naughton