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 = (
  <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>
22 users liked answer #0dislike answer #022
Qwerty profile pic
Qwerty

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.

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

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
yonatanmn

You can do this using AirBnB’s Enzyme library

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

https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md#text--string

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 => {
  afterEach(cleanup);
  it("renders properly", (): void => {
    const { container } = render(
      <MyComponent prop1="myprop1" prop2="myprop2" />
    );
    expect(container).toMatchSnapshot();
  });
});

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

Copyright © 2022 QueryThreads

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