Skip to content

Ensure waitForElement disconnects MutationObserver at the right time #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/__tests__/wait-for-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,3 +312,48 @@ test('it returns immediately if the callback returns the value before any mutati

return promise
})

test('does not get into infinite setTimeout loop after MutationObserver notification', async () => {
const {container} = render(`<div data-testid="initial-element"></div>`)

let didMakeMutation = false
const callback = jest.fn(() => didMakeMutation).mockName('callback')
const successHandler = jest.fn().mockName('successHandler')
const errorHandler = jest.fn().mockName('errorHandler')
jest.useFakeTimers()

const promise = waitForElement(callback, {
container,
timeout: 70,
mutationObserverOptions: {attributes: true},
}).then(successHandler, errorHandler)

// Expect 2 timeouts to be scheduled:
// - waitForElement timeout
// - MutationObserver timeout
expect(setTimeout).toHaveBeenCalledTimes(2)

// One synchronous `callback` call is expected.
expect(callback).toHaveBeenCalledTimes(1)
expect(successHandler).toHaveBeenCalledTimes(0)
expect(errorHandler).toHaveBeenCalledTimes(0)

// Make a mutation so MutationObserver calls out callback
container.setAttribute('data-test-attribute', 'something changed')
didMakeMutation = true

// Advance timer to expire MutationObserver timeout
jest.advanceTimersByTime(50)
jest.runAllImmediates()
await promise
expect(setTimeout).toHaveBeenCalledTimes(3)

// Expect callback and successHandler to be called
expect(callback).toHaveBeenCalledTimes(2)
expect(successHandler).toHaveBeenCalledTimes(1)
expect(errorHandler).toHaveBeenCalledTimes(0)

// Expect no more setTimeout calls
jest.advanceTimersByTime(100)
expect(setTimeout).toHaveBeenCalledTimes(3)
})
2 changes: 1 addition & 1 deletion src/wait-for-element.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function waitForElement(
let lastError, observer, timer // eslint-disable-line prefer-const
function onDone(error, result) {
clearTimeout(timer)
observer.disconnect()
setImmediate(() => observer.disconnect())
if (error) {
reject(error)
} else {
Expand Down