From 57d699b6c15a600e11d788a980e2bfdb34112802 Mon Sep 17 00:00:00 2001 From: Sam Horton Date: Wed, 31 Jul 2019 15:10:19 -0700 Subject: [PATCH] fix: getByRole error message, when there are no available roles --- src/__tests__/element-queries.js | 2 +- src/__tests__/role.js | 13 +++++++++++++ src/queries/role.js | 22 ++++++++++++++++------ 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/__tests__/element-queries.js b/src/__tests__/element-queries.js index c01c0763..1fa122b3 100644 --- a/src/__tests__/element-queries.js +++ b/src/__tests__/element-queries.js @@ -88,7 +88,7 @@ test('get throws a useful error message', () => { expect(() => getByRole('LucyRicardo')).toThrowErrorMatchingInlineSnapshot(` "Unable to find an element with the role "LucyRicardo" -Here are the available roles: +There are no available roles.
diff --git a/src/__tests__/role.js b/src/__tests__/role.js index 77aa9ee1..30e6b259 100644 --- a/src/__tests__/role.js +++ b/src/__tests__/role.js @@ -20,3 +20,16 @@ Here are the available roles:
" `) }) + +test('logs error when there are no available roles', () => { + const {getByRole} = render('
') + expect(() => getByRole('article')).toThrowErrorMatchingInlineSnapshot(` +"Unable to find an element with the role "article" + +There are no available roles. + +
+
+
" +`) +}) diff --git a/src/queries/role.js b/src/queries/role.js index 9ce1fccc..6792b5ab 100644 --- a/src/queries/role.js +++ b/src/queries/role.js @@ -26,16 +26,26 @@ function queryAllByRole( const getMultipleError = (c, role) => `Found multiple elements with the role "${role}"` -const getMissingError = (container, role) => - ` -Unable to find an element with the role "${role}" +const getMissingError = (container, role) => { + const roles = prettyRoles(container) + let roleMessage + + if (roles.length === 0) { + roleMessage = 'There are no available roles.' + } else { + roleMessage = ` Here are the available roles: - ${prettyRoles(container) - .replace(/\n/g, '\n ') - .replace(/\n\s\s\n/g, '\n\n')} + ${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')} `.trim() + } + + return ` +Unable to find an element with the role "${role}" + +${roleMessage}`.trim() +} const [ queryByRole,