diff --git a/src/__tests__/role.js b/src/__tests__/role.js index a187a77b..29eec2a2 100644 --- a/src/__tests__/role.js +++ b/src/__tests__/role.js @@ -346,7 +346,9 @@ Here are the accessible roles: test('has no useful error message in findBy', async () => { const {findByRole} = render(`
  • `) - await expect(findByRole('option', {timeout: 1})).rejects.toThrow('Unable to find role="option"') + await expect(findByRole('option', {timeout: 1})).rejects.toThrow( + 'Unable to find role="option"', + ) }) test('explicit role is most specific', () => { @@ -378,6 +380,62 @@ Here are the accessible roles: `) }) +test('accessible regex name in error message for multiple found', () => { + const {getByRole} = render( + ``, + ) + + expect(() => getByRole('button', {name: /value/i})) + .toThrowErrorMatchingInlineSnapshot(` +"Found multiple elements with the role "button" and name \`/value/i\` + +(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)). + +
    + + + +
    " +`) +}) + +test('accessible string name in error message for multiple found', () => { + const {getByRole} = render( + ``, + ) + + expect(() => getByRole('button', {name: 'Submit'})) + .toThrowErrorMatchingInlineSnapshot(` +"Found multiple elements with the role "button" and name "Submit" + +(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)). + +
    + + + +
    " +`) +}) + describe('configuration', () => { let originalConfig beforeEach(() => { diff --git a/src/queries/role.js b/src/queries/role.js index 07fe0771..1d9d3211 100644 --- a/src/queries/role.js +++ b/src/queries/role.js @@ -107,8 +107,18 @@ function queryAllByRole( }) } -const getMultipleError = (c, role) => - `Found multiple elements with the role "${role}"` +const getMultipleError = (c, role, {name} = {}) => { + let nameHint = '' + if (name === undefined) { + nameHint = '' + } else if (typeof name === 'string') { + nameHint = ` and name "${name}"` + } else { + nameHint = ` and name \`${name}\`` + } + + return `Found multiple elements with the role "${role}"${nameHint}` +} const getMissingError = ( container,