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

Kev D. picture Kev D. · Apr 22, 2020 · Viewed 9.1k times · Source

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...

Answer

Tom picture Tom · Apr 23, 2020

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')