I'm trying to test a react component children and I wanted to get a text representation of its children.
Is there a tool that does something similar to node.textContent
for React?
I would like to have something like this:
let testComponent = (
<Test>
<p>abc</p>
<p>abc2</p>
</Test>
);
expect(testComponent.props.children.toString()).to.equal('abc abc2');
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 picture
{heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
<pre ref={printInnerHTML}/>
<pre>{getNodeText(heading)}</pre>
You can write a small function that traverses through the react element and gets you the text.
import React from 'react';
import renderer from 'react-test-renderer';
const MyComponent = ()=>{
return <div>
<p>hello</p>
<div>
<p>to</p>
</div>
</div>
}
const getText=(tree)=>{
if(typeof tree === 'string'){
return tree;
}
return tree.children.map((child)=>{
return getText(child);
}).join('');
}
it('renders without crashing', () => {
const tree = renderer
.create(<MyComponent />)
.toJSON();
expect(getText(tree)).toBe("helloto");
});
Here MyComponent is the component from which you need the text.
getText() will get all the text nodes from the component in the form of a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With