Fotios Tsakiris
Fotios Tsakiris

Reputation: 1558

Why getByRole does not accept the "ul" as a string?

I'm testing a React app with React Testing Library.
I try to get a ul element like this:

const { render, getByRole } = require("@testing-library/react");
const { default: MoviesList } = require("../components/MoviesList");
const { default: MoviesProvider } = require("../utils/MoviesProvider");

describe("<MoviesList />", () => {
  it("Component should exist", () => {
    render(
      <MoviesProvider value={{}}>
        <MoviesList />
      </MoviesProvider>
    );


    const ul = getByRole('ul');

    expect(ul).toBeInTheDocument()

    // or
    expect(getByRole("ul"), isInTheDocument);

  });
});

But I get this error:

TypeError: Expected container to be an Element, a Document or a DocumentFragment but got string.

Am I doing something wrong?

Upvotes: 0

Views: 1169

Answers (2)

Fotios Tsakiris
Fotios Tsakiris

Reputation: 1558

The problem was that I was importing getByRole on the top from @testing-library/react. When I tried to import it from render it worked.

Can anyone explain why?

const { getByRole } = render(
      <MoviesProvider value={{}}>
        <MoviesList />
      </MoviesProvider>
    );


    const list = getByRole('list');

Upvotes: 0

aquinq
aquinq

Reputation: 1448

ul is an element, not an accessibility role. The corresponding role is list :

const ul = getByRole('list');
expect(ul).toBeInTheDocument()

You can find a list of existing roles here https://www.w3.org/TR/wai-aria/#role_definitions

Upvotes: 1

Related Questions