Skip to content

Commit

Permalink
feat: Improve performance of ByRole in waitFor* (#590)
Browse files Browse the repository at this point in the history
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
  • Loading branch information
eps1lon and kentcdodds committed May 28, 2020
1 parent 2a366f8 commit 709044b
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions src/__tests__/role.js
Expand Up @@ -343,6 +343,12 @@ Here are the accessible roles:
`)
})

test('has no useful error message in findBy', async () => {
const {findByRole} = render(`<li />`)

await expect(findByRole('option', {timeout: 1})).rejects.toThrow('Unable to find role="option"')
})

test('explicit role is most specific', () => {
const {getByRole} = renderIntoDocument(
`<button role="tab" aria-label="my-tab" />`,
Expand Down
10 changes: 10 additions & 0 deletions src/config.js
Expand Up @@ -27,6 +27,16 @@ let config = {
error.name = 'TestingLibraryElementError'
return error
},
_disableExpensiveErrorDiagnostics: false,
}

export function runWithExpensiveErrorDiagnosticsDisabled(callback) {
try {
config._disableExpensiveErrorDiagnostics = true
return callback()
} finally {
config._disableExpensiveErrorDiagnostics = false
}
}

export function configure(newConfig) {
Expand Down
4 changes: 4 additions & 0 deletions src/queries/role.js
Expand Up @@ -112,6 +112,10 @@ const getMissingError = (
role,
{hidden = getConfig().defaultHidden, name} = {},
) => {
if (getConfig()._disableExpensiveErrorDiagnostics) {
return `Unable to find role="${role}"`
}

let roles = ''
Array.from(container.children).forEach(childElement => {
roles += prettyRoles(childElement, {
Expand Down
4 changes: 2 additions & 2 deletions src/wait-for.js
Expand Up @@ -6,7 +6,7 @@ import {
clearTimeout,
runWithRealTimers,
} from './helpers'
import {getConfig} from './config'
import {getConfig, runWithExpensiveErrorDiagnosticsDisabled} from './config'

// This is so the stack trace the developer sees is one that's
// closer to their code (because async stack traces are hard to follow).
Expand Down Expand Up @@ -60,7 +60,7 @@ function waitFor(

function checkCallback() {
try {
onDone(null, callback())
onDone(null, runWithExpensiveErrorDiagnosticsDisabled(callback))
// If `callback` throws, wait for the next mutation or timeout.
} catch (error) {
// Save the callback error to reject the promise with it.
Expand Down

0 comments on commit 709044b

Please sign in to comment.