Skip to content

Commit d5b3f35

Browse files
fix(waitForElementToBeRemoved): Make initial check work with getBy*.
This commit includes a regression test. Fixes testing-library#1093.
1 parent d578c7e commit d5b3f35

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

src/__tests__/wait-for-element-to-be-removed.js

+11
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,17 @@ test('requires an unempty array of elements to exist first (function form)', ()
8080
)
8181
})
8282

83+
test('requires a getBy* query to not throw first', () => {
84+
const {getByTestId} = renderIntoDocument(`
85+
<div data-testid="div"></div>
86+
`)
87+
return expect(
88+
waitForElementToBeRemoved(() => getByTestId('non-existing-testid')),
89+
).rejects.toThrowErrorMatchingInlineSnapshot(
90+
`The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.`,
91+
)
92+
})
93+
8394
test('after successful removal, fullfills promise with empty value (undefined)', () => {
8495
const {getByTestId} = renderIntoDocument(`
8596
<div data-testid="div"></div>

src/wait-for-element-to-be-removed.js

+18-11
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,28 @@ function initialCheck(elements) {
1212
}
1313
}
1414

15+
function wrapFunctionCallback(callback) {
16+
return () => {
17+
try {
18+
return callback()
19+
} catch (error) {
20+
if (error.name === 'TestingLibraryElementError') {
21+
return null
22+
}
23+
throw error
24+
}
25+
}
26+
}
27+
1528
async function waitForElementToBeRemoved(callback, options) {
1629
// created here so we get a nice stacktrace
1730
const timeoutError = new Error('Timed out in waitForElementToBeRemoved.')
18-
if (typeof callback !== 'function') {
19-
initialCheck(callback)
31+
if (typeof callback === 'function') {
32+
callback = wrapFunctionCallback(callback)
33+
} else {
2034
const elements = Array.isArray(callback) ? callback : [callback]
2135
const getRemainingElements = elements.map(element => {
36+
if (!element) return () => null
2237
let parent = element.parentElement
2338
if (parent === null) return () => null
2439
while (parent.parentElement) parent = parent.parentElement
@@ -30,15 +45,7 @@ async function waitForElementToBeRemoved(callback, options) {
3045
initialCheck(callback())
3146

3247
return waitFor(() => {
33-
let result
34-
try {
35-
result = callback()
36-
} catch (error) {
37-
if (error.name === 'TestingLibraryElementError') {
38-
return undefined
39-
}
40-
throw error
41-
}
48+
const result = callback()
4249
if (!isRemoved(result)) {
4350
throw timeoutError
4451
}

0 commit comments

Comments
 (0)