testing-library / dom-testing-library

šŸ™ Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.25k stars 460 forks source link

getByText not working with multiline text #1285

Open cristiancundari opened 5 months ago

cristiancundari commented 5 months ago

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.