diff --git a/src/__tests__/wait-for-element-to-be-removed.js b/src/__tests__/wait-for-element-to-be-removed.js
index 8ca1a83a..720c0ba2 100644
--- a/src/__tests__/wait-for-element-to-be-removed.js
+++ b/src/__tests__/wait-for-element-to-be-removed.js
@@ -42,6 +42,20 @@ test('requires an element to exist first', () => {
)
})
+test("requires element's parent to exist first", () => {
+ const {getByTestId} = renderIntoDocument(`
+
asd
+`)
+ const div = getByTestId('div')
+ div.parentElement.removeChild(div)
+
+ return expect(
+ waitForElementToBeRemoved(div),
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
+ `"The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal."`,
+ )
+})
+
test('requires an unempty array of elements to exist first', () => {
return expect(
waitForElementToBeRemoved([]),
diff --git a/src/wait-for-element-to-be-removed.js b/src/wait-for-element-to-be-removed.js
index d69974f4..ff9adb9d 100644
--- a/src/wait-for-element-to-be-removed.js
+++ b/src/wait-for-element-to-be-removed.js
@@ -20,6 +20,7 @@ async function waitForElementToBeRemoved(callback, options) {
const elements = Array.isArray(callback) ? callback : [callback]
const getRemainingElements = elements.map(element => {
let parent = element.parentElement
+ if(parent === null) return () => null
while (parent.parentElement) parent = parent.parentElement
return () => (parent.contains(element) ? element : null)
})