Reputation: 34061
I have written the following test:
test("Search for particular text", async () => {
render(<Home/>)
expect(screen.getByText("TARGADS")).toBeInTheDocument()
expect(screen.getByText("WE BRING YOU TO THE NEXT OF THE ADVERTISEMENT")).toBeInTheDocument()
expect(screen.getByText("For your shared interests")).toBeInTheDocument()
screen.debug()
})
The last test failed because of:
TestingLibraryElementError: Unable to find an element with the text: For your shared interests. This could be because the text is broken up by multiple elements.
when I look into the rendered DOM:
...
<div
class="MuiGrid-root MuiGrid-container MuiGrid-item MuiGrid-grid-sm-12"
>
<div
class="MuiGrid-root makeStyles-textContainer-4 MuiGrid-item MuiGrid-grid-sm-12 MuiGrid-grid-md-6"
style="background: rgb(255, 10, 84);"
>
<h4
class="MuiTypography-root makeStyles-text-5 MuiTypography-h4"
>
For your shared interests, you will receive 5% of our earnings for every single interestSo do not hesitate to share. Share more earn more!!!
</h4>
</div>
<div
class="MuiGrid-root MuiGrid-container MuiGrid-item MuiGrid-align-items-xs-center MuiGrid-justify-xs-center MuiGrid-grid-xs-12 MuiGrid-grid-md-6"
>
<img
alt="Earning money"
class="makeStyles-mediaIcon-6"
src="money.svg"
/>
</div>
</div>
</div>
The text appears. What am I doing wrong?
Upvotes: 1
Views: 2505
Reputation: 1807
You are getting that output because the screen couldn't find any DOM element that has innerText "For your shared interests".
This line:
expect(screen.getByText("For your shared interests")).toBeInTheDocument()
Will try to get anything in the DOM that contains just 'For your shared interests'
inside. So, based on your output HTML that line should be something like this:
expect(screen.getByText("For your shared interests, you will receive 5% of our earnings for every single interestSo do not hesitate to share. Share more earn more!!!")).toBeInTheDocument()
But that looks really complicated, and assumming that you are showing some dynamic data there, you could use a regular expression in getByText
function. Like this:
expect(screen.getByText(/For your shared interests/)).toBeInTheDocument()
Upvotes: 1