Skip to content

Images with alt attributes cannot be grabbed ByRole #1235

Closed
@brtrick

Description

@brtrick
  • @testing-library/dom version: 9.3.0
  • Testing Framework and version: Jest/React
  • DOM Environment:

The Issue

If an img tag has an alt attribute, its role shows up as presentation instead of as img. So, e.g., this test:

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

test("Displays an img", () => {
  render (<img src="https://http.cat/418" alt="404" />);
  screen.getByRole('img')
})

produces this result:

ImgError

ARIA Background

According to the ARIA docs an img should only default to the role of presentation if it has an alt attribute equal to "":

AriaImg

Source of the Problem and Proposed Solution

The problem arises when the selector is being made in role-helpers.js:

function buildElementRoleList(elementRolesMap) {
function makeElementSelector({name, attributes}) {
return `${name}${attributes
.map(({name: attributeName, value, constraints = []}) => {
const shouldNotExist = constraints.indexOf('undefined') !== -1
if (shouldNotExist) {
return `:not([${attributeName}])`
} else if (value) {
return `[${attributeName}="${value}"]`
} else {
return `[${attributeName}]`
}
})
.join('')}`
}

Because a value of "" resolves to false in line 87, the selector for a presentation img ends up returning [alt] instead of [alt=""] as its characteristic attribute, meaning that any img with an alt attribute will be marked with a presentation role. Simply adding an explicit check for value === "" on line 87 fixes the issue. (The check could be made more specific if that is needed.)

I will submit a PR with the proposed fix and updated tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions