@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:
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 "":

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.
@testing-library/domversion: 9.3.0The Issue
If an
imgtag has analtattribute, its role shows up aspresentationinstead of asimg. So, e.g., this test:produces this result:
ARIA Background
According to the ARIA docs an
imgshould only default to the role ofpresentationif it has analtattribute equal to "":Source of the Problem and Proposed Solution
The problem arises when the selector is being made in
role-helpers.js:dom-testing-library/src/role-helpers.js
Lines 80 to 94 in d09b3c2
Because a value of
""resolves to false in line 87, the selector for a presentationimgends up returning[alt]instead of[alt=""]as its characteristic attribute, meaning that anyimgwith analtattribute will be marked with apresentationrole. Simply adding an explicit check forvalue === ""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.