Search code examples
react-testing-library

Every image gets presentational role


My tests fail due to images getting "presentation" role. Is it something that's expected? Note: I would like to avoid doing <img role="img" ... />.

test('component', () => {
  render(<Component {...defaultProps} />);
  expect(screen.getByRole('img')).toBeInTheDocument();
});
TestingLibraryElementError: Unable to find an accessible element with
the role "img"

Here are the accessible roles:

  presentation:

  Name "logo":   

      <img
        alt="logo"
        src="https://google.com/images/logo.png"   
     />


Solution

  • This is a bug introduced in aria-query@5.2.0, which you're exposed to transitively via @testing-library/react's dependency on @testing-library/dom:

    Until an upstream fix is available, @testing-library/dom@8.20.1 and @testing-library/dom@9.3.1 pin the dependency to aria-query@5.1.3. Either upgrade to those versions or (if you're using NPM 8.3 or above) add:

      "overrides": {
        "aria-query": "5.1.3"
      },
    

    to your package file then reinstall.


    Note that this won't entirely solve image-selecting problems, as the conformance test shared in the above issue fails for either version (albeit for different reasons):

    • aria-query@5.1.3: img elements always have img role

        W3C Recommendations: https://www.w3.org/TR/html-aria/#docconformance
          ✓ img with no alt has an img role (26 ms)
          ✕ img with an empty alt has a presentation role (2 ms)
          ✓ img with a non-empty alt has an img role (6 ms)
      
    • aria-query@5.2.1: img elements with alt attributes always have presentation role

        W3C Recommendations: https://www.w3.org/TR/html-aria/#docconformance
          ✓ img with no alt has an img role (28 ms)
          ✓ img with an empty alt has a presentation role (7 ms)
          ✕ img with a non-empty alt has an img role (1 ms)