testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Home Page:https://testing-library.com/react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

getByRole ignores role "link" on achors without href attribute or falsy value

MarcoSmeuldersVisma opened this issue · comments

The getByRole selector won't find a anchor by its "link" role when the href attribute has an empty string, or is missing. Code to reproduce:

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

test("will find role", () => {
  render(<a href={"/test"}>demo</a>);

  expect(screen.getByRole("link")).toHaveTextContent("demo")
});

test("will NOT find role", () => {
  render(<a href={""}>demo</a>);

  // Unable to find an accessible element with the role "link"
  expect(screen.getByRole("link")).toHaveTextContent("demo")
});

Using screen.getByRole("link", { hidden: true }) has no effect.

For accessibility purposes, this might be a sane choice. But no-where in any documentation I'm able to find the requirement for ignoring the "link" role from an anchor when a href value is falsy. So I think this is a bug.

I didn't have this issue in version 7.x but in version 8.x it appeared.

@MarcoSmeuldersVisma the implicit role for anchor tag without an href is "generic" as can be seen in the ARIA spec:
image

https://www.w3.org/TR/html-aria/

Wow. I totally missed that one. It must have been a long day yesterday. Thanks!

I'll consider using screen.getAllByRole("generic").find(el => el.hasAttribute("href")) or container.querySelector("[href]") for this use case. But I might end up rethinking my test eventually because the link might be inaccessible for users and requires an alternative solution.