React Jest how to test if a span contains some certain text from mount snapshot?

15,234

find returns a ReactWrapper like mount, so you can chain find calls.

For example, something like this.

widget.find('[id="divHeader"]').find('h2').find('span').text().contains('English')
Share:
15,234
Kev D.
Author by

Kev D.

Updated on July 08, 2022

Comments

  • Kev D.
    Kev D. almost 2 years

    I am testing a component that does not have any id for me to be able to select from Jest, my mounted component snapshot will be like

    <div id='divHeader'>
        <h2
          className=""
          style={Object {}}
        >
          <span
            className=""
            style={Object {}}
          >
            This is an English text
          </span>
        </h2>
    </div>
    

    So is there any way for me to verify that the text inside my span from the snapshot would contain the world English, something like

    widget = mount(<MyComponent {...defaultProp} />);
    // widget.find('span').text.contains('English')   
    // widget.find('[id="divHeader"]').h2.span.text.contains('English')
    

    I am having some trouble in the find here where I know it can find the element by id, but unfortunately I cannot assign any id to my span, and even I can find my div by id, I cannot select its children element like div->h2->span...

  • Kev D.
    Kev D. about 4 years
    Awesome! Somehow the text does not work for me, I have to use ....find('span').props().children which gives me the inner html text, is that expected? the find('span') will return the ReactWrapper which I don't know what's inside when I do the console.log(...find('span'))
  • Tom
    Tom about 4 years
    ah text is a function not a prop value. .text(). find returns a ReactWapper not a domnode.
  • Tom
    Tom about 4 years
    also debug is helpful. console.log(wrap.find(...).debug())