reactjsunit-testingjestjsreact-testing-library

How to query by text string which contains html tags using React Testing Library?


Current Working Solution

Using this html:

<p data-testid="foo">Name: <strong>Bob</strong> <em>(special guest)</em></p>

I can use the React Testing Library getByTestId method to find the textContent:

expect(getByTestId('foo').textContent).toEqual('Name: Bob (special guest)')

Is there a better way?

I would like to simply use this html:

<p>Name: <strong>Bob</strong> <em>(special guest)</em></p>

And use React Testing Library's getByText method like this:

expect(getByText('Name: Bob (special guest)')).toBeTruthy()

But this does not work.

So, the question…

Is there a simpler way to use React Testing Library to find strings of text content with the tags striped out?


Solution

  • If you are using testing-library/jest-dom in your project. You can also use toHaveTextContent.

    expect(getByTestId('foo')).toHaveTextContent('Name: Bob (special guest)')
    

    if you need a partial match, you can also use regex search patterns

    expect(getByTestId('foo')).toHaveTextContent(/Name: Bob/)
    

    Here's a link to the package