'RTL: how to test the html content of the whole component
I have a component which renders some conditional text on the basis of a prop. i want to test the rendered text. I can do that by getting a reference to the container from render and then chekcing container to have or not have a particular text content
const { container } = render(...);
expect(container).toHaveTextContent(...);
But, as the current suggestion is to use screen instead of render, which is more convenient to use generally, i am trying to figure out if this is possible with screen.
is there a way to have this test with screen instead of container?
I can may be use a test-id on the container div of my component and target that using screen.getByTestId, but that looksike overkill
Solution 1:[1]
If the text you are looking for is inside an accessible element, such as a text field, button, etc, then it's always best to use one of the specific queries: getByRole, getByLabelText, etc, to find the text and assert on it. That would be very easy to test, e.g. screen.getByRole('button').toHaveText(.
Alternatively, if you cannot narrow the query down using one of the aforementioned queries, then you can do expect(screen.getByText(/your text content/i)).toHaveTextContent(...);
This works well, but if the text isn't unique, it can be difficult to find elements, so you may need to go back to lean on: https://testing-library.com/docs/dom-testing-library/api-within/ (see React tab) or finally a test-id.
Solution 2:[2]
You can have an expectation in your component using screen like this:
expect(screen.getByRole("button").textContent).toMatchInlineSnapshot();
This will fill up the brackets of toMatchInlineSnapshot() with whatever the text content it received based on whatever your props are like this:
toMatchInlineSnapshot(`"expected text content"`)`
If you are targeting whole container, you will have to then use container query like so:
const { container } = render(...);
expect(container).toMatchInlineSnapshot()
and then run test, which will then fill brackets of toMatchInlineSnapshot() with the HTML like so:
expect(container).toMatchInlineSnapshot(`
<div>
<p>Hello World</p>
</div>
`)
For more, refer here: Snapshot Testing
For better queries, you can try using Testing-Playground Chrome Extension
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ourmaninamsterdam |
| Solution 2 |
