Source:  Twitter logo

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 = (

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'')
  if (typeof node === 'object' && node) return getNodeText(node.props.children)

  // in the picture
  {heading} // <Heading>Hello <span className="red">Code</span>Sandbox</Heading>
  <pre ref={printInnerHTML}/>
22 users liked answer #0dislike answer #022
Qwerty profile pic

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>

const getText=(tree)=>{
  if(typeof tree === 'string'){
    return tree;
    return getText(child);

it('renders without crashing', () => {
  const tree = renderer
    .create(<MyComponent />)


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.

2 users liked answer #1dislike answer #12
Atul profile pic

you can use getDomNode() or findDomNode() for es6 Components, and then use normal DOM methods.

If your'e looking for the React way - There shouldn't be one, since a parent is quite blind of its children.

0 users liked answer #2dislike answer #20
yonatanmn profile pic

You can do this using AirBnB’s Enzyme library

shallow(<Foo>bar</Foo>).text  // bar

0 users liked answer #3dislike answer #30
David Bradshaw profile pic
David Bradshaw

Definitely you should try Jest (I usually use it together with the React Testing Library). Basically, you can take a snapshot of your component, so, you can test not only the text contained in your component, but you can also test the layout, the parameters of the elements, etc. It is very handy to detect unwanted changes. It also comes with great features as code coverage:

import React from 'react';
import { cleanup, render } from "@testing-library/react";
import { MyComponent } from "./MyComponent";

describe("MyComponent", (): void => {
  it("renders properly", (): void => {
    const { container } = render(
      <MyComponent prop1="myprop1" prop2="myprop2" />

0 users liked answer #4dislike answer #40
ElChiniNet profile pic

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).