Skip to content

"Cannot read property 'test' of undefined." when undefined passed to matches #717

@JoshuaKGoldberg

Description

@JoshuaKGoldberg
  • @testing-library/dom version: 7.19.0
  • Testing Framework and version: jest@26.1.0 and @testing-library/react@10.4.7
  • DOM Environment: jsdom@11.12.0

Relevant code or config:

const view = render(<div />);

view.getByRole(undefined);

What you did:

In a project that does not use TypeScript (alas!), I passed undefined instead of a valid matcher to getByRole.

What happened:

TypeError: Cannot read property 'test' of undefined

       9 |     const view = render(<div />);
      10 | 
    > 11 |     view.getByRole(undefined);
         |          ^
      13 | 

      at matches (../../node_modules/@testing-library/dom/dist/matches.js:39:20)
      at ../../node_modules/@testing-library/dom/dist/queries/role.js:78:47
          at Array.some (<anonymous>)
      at ../../node_modules/@testing-library/dom/dist/queries/role.js:78:26
          at Array.filter (<anonymous>)
      at queryAllByRole (../../node_modules/@testing-library/dom/dist/queries/role.js:57:54)
      at ../../node_modules/@testing-library/dom/dist/query-helpers.js:89:17
      at ../../node_modules/@testing-library/dom/dist/query-helpers.js:64:17
      at getByRole (../../node_modules/@testing-library/dom/dist/query-helpers.js:108:19)

Reproduction:

https://codesandbox.io/s/react-testing-library-getbytext-undefined-r6ygs for a version showing null and getByText causing the same issue.

Problem description:

For all matchers that eventually call to matches, including getByText and getByRole, passing an invalid matcher such as null or undefined crashes with a confusing error message. Users likely did not mean to pass an invalid matcher to the search.

return matcher.test(normalizedText)

Suggested solution:

Similar to #609, I'd like to send a PR that adds an explicit error message for this case.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions