Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getByText not working with multiline text #1285

Open
cristiancundari opened this issue Jan 19, 2024 · 0 comments
Open

getByText not working with multiline text #1285

cristiancundari opened this issue Jan 19, 2024 · 0 comments

Comments

@cristiancundari
Copy link

  • @testing-library/dom version: 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant