Skip to content

Commit d966008

Browse files
SavePointSamKent C. Dodds
authored andcommitted
fix: getByRole error message, when there are no available roles (#330)
1 parent 320d940 commit d966008

File tree

3 files changed

+30
-7
lines changed

3 files changed

+30
-7
lines changed

src/__tests__/element-queries.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ test('get throws a useful error message', () => {
8888
expect(() => getByRole('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(`
8989
"Unable to find an element with the role "LucyRicardo"
9090
91-
Here are the available roles:
91+
There are no available roles.
9292
9393
<div>
9494
<div />

src/__tests__/role.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,16 @@ Here are the available roles:
2020
</div>"
2121
`)
2222
})
23+
24+
test('logs error when there are no available roles', () => {
25+
const {getByRole} = render('<div />')
26+
expect(() => getByRole('article')).toThrowErrorMatchingInlineSnapshot(`
27+
"Unable to find an element with the role "article"
28+
29+
There are no available roles.
30+
31+
<div>
32+
<div />
33+
</div>"
34+
`)
35+
})

src/queries/role.js

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,26 @@ function queryAllByRole(
2626

2727
const getMultipleError = (c, role) =>
2828
`Found multiple elements with the role "${role}"`
29-
const getMissingError = (container, role) =>
30-
`
31-
Unable to find an element with the role "${role}"
3229

30+
const getMissingError = (container, role) => {
31+
const roles = prettyRoles(container)
32+
let roleMessage
33+
34+
if (roles.length === 0) {
35+
roleMessage = 'There are no available roles.'
36+
} else {
37+
roleMessage = `
3338
Here are the available roles:
3439
35-
${prettyRoles(container)
36-
.replace(/\n/g, '\n ')
37-
.replace(/\n\s\s\n/g, '\n\n')}
40+
${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')}
3841
`.trim()
42+
}
43+
44+
return `
45+
Unable to find an element with the role "${role}"
46+
47+
${roleMessage}`.trim()
48+
}
3949

4050
const [
4151
queryByRole,

0 commit comments

Comments
 (0)