testing-library / testing-library/dom-testing-library
getByText not working with multiline text
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 3.3k
- Forks
- 474
- PR merge metrics
- No merged PRs in 30d
Description
@testing-library/domversion: 9.3.4- Testing Framework and version: next 13.5.1
- jest version: ^29.7.0
- DOM Environment:
- jest-dom version: ^6.2.0
Relevant code or config:
it("Should pass", () => {
const MyComponent = ({ text }: { text: string }) => {
return <p>{text}</p>;
};
const multilineText = "Line1\nLine2";
render(<MyComponent text={multilineText} />);
expect(screen.getByText(multilineText)).toBeInTheDocument();
});
What you did:
Executing the code above, I would expect the test to pass, but getByText function cannot find the element in the DOM.
FAIL __tests__/example.test.tsx
× Should pass (20 ms)
● Should pass
TestingLibraryElementError: Unable to find an element with the text: Line1 Line2 (normalized from 'Line1
Line2'). This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, script, style
<body>
<div>
<p>
Line1
Line2
</p>
</div>
</body>
10 | const multilineText = "Line1\nLine2";
11 | render(<MyComponent text={multilineText} />);
> 12 | expect(screen.getByText(multilineText)).toBeInTheDocument();
| ^
13 | });
14 |
at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
at node_modules/@testing-library/dom/dist/query-helpers.js:76:38
at node_modules/@testing-library/dom/dist/query-helpers.js:52:17
at getByText (node_modules/@testing-library/dom/dist/query-helpers.js:95:19)
at Object.<anonymous> (__tests__/example.test.tsx:12:17)
Reproduction:
Problem description:
I think it should be able to find the element because in my component I'm just rendering the exact text I provide to the getByText function.
Suggested solution:
If I understand correctly, the matcher only normalizes the string I pass as a parameter but not the node text, which is why it will never be equal.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in tests/example.test.tsx and trace getByText through the query-helpers.js stack path shown in the failure. Check how multiline text is normalized, then verify that the reproduction passes while the existing text-matching behavior remains covered.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- testing-qa
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100