React Testing Library getByRole('heading') how to get node with a specific heading level

Viewed 8904

I have a h1 tag and I'm trying to get the node using specific heading level but running to the error:

Found multiple elements with the role "heading"

According the documentation this query supposed to return only h1.

here is the example:

import React from "react";
import { render, screen } from "@testing-library/react";

it("Should found only header1", async () => {
  render(
    <div>
      <h1>editable content</h1>
      <p>and</p>
      <h2>other header</h2>
    </div>
  );
  screen.debug(screen.getByRole("heading", { level: 1 }));
});

and here is the error:

    Found multiple elements with the role "heading"

    (If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).

    <body>
      <div>
        <div>
          <h1>
            editable content
          </h1>
          <p>
            and
          </p>
          <h2>
            other header
          </h2>
        </div>
      </div>
    </body>

1 Answers

Solved.
The reason is the version of the library. By default create-react-app installing outdated version of @testing-library.
Run CLI command npm outdated and check the versions of dependencies:

Package                      Current  Wanted  Latest
@testing-library/jest-dom      4.2.4   4.2.4  5.11.4
@testing-library/react         9.5.0   9.5.0  11.0.2
@testing-library/user-event    7.2.1   7.2.1  12.1.4

To update dependencies open package.json and manually update them to the latest:

  ...
  "dependencies": {
    ...
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.0.2",
    "@testing-library/user-event": "^12.1.4"
    ...
  },
  ...

Save changes and run CLI command: npm install

Related