testing-library/testing-library-docs

How does ByAltText query work with aria-label

tnyo43 opened this issue · 1 comments

Describe the bug A clear and concise description of what the bug is.

There is a following sentence in ByRole docs.

For example <img aria-label="fancy image" src="fancy.jpg" /> will be returned for both getByAltText('fancy image') and getByRole('img', { name: 'fancy image' }).

I found that getByAltText doesn't seem to return element only with aria-label attribute.

To Reproduce Steps to reproduce the behavior:

  1. create and run a following test:
import { render, screen } from "@testing-library/react";

describe("find element with aria-label", () => {
  beforeEach(() => {
    render(<img aria-label="fancy image" src="fancy.jpg" />);
  });

  test("ByRole query", () => {
    expect(
      screen.getByRole("img", { name: "fancy image" })
    ).toBeInTheDocument();
  });

  test("ByAltText query", () => {
    expect(screen.getByAltText("fancy image")).toBeInTheDocument();
  });
});
  1. "ByAltText query" testcase will fail

the error message is:

Unable to find an element with the alt text: fancy image
Ignored nodes: comments, script, style
<body>
  <div>
    <img
      aria-label="fancy image"
      src="fancy.jpg"
    />
  </div>
</body>

You can see the behavior in this sandbox. Click the Tests tab in the right pane to run the test.

Expected behavior A clear and concise description of what you expected to happen.

I'm not sure. Maybe I misunderstand something and created wrong test.

Sandbox info

  • node: v14.18.1 (by default)
  • react: v18.2.0
  • react-dom: 18.2.0
  • react-scripts: v4.0.3
  • @testing-library/jest-dom: v5.16.5
  • @testing-library/react: v13.4.0

Additional context Add any other context about the problem here.

If I use alt attribute instead of aria-label, the tests pass. (see sandbox as well)

I think that the img element should be updated to using the alt attribute:

<img alt="fancy image" src="fancy.jpg" />