How To Test An Async Function In An Event Listener With Jest?
I have an event listener that runs an asynchronous function, and removes some elements from the DOM after completion: async function fetchAndRemove() { try { const response =
Solution 1:
This is wrong because DOM events don't involve promises and await Promise.resolve
is redundant:
awaitPromise.resolve(document.querySelector('.my-button').click())
It creates one-tick delay and that's all.
Since fetchAndRemove
is referred in the same module it's defined, it cannot be spied, so fetch
promise should be chained in order to maintain correct execution order.
Considering that fetch
is a spy, it can be:
fetch.mockResponse(JSON.stringify({ status: 'Success' }))
setupListeners()
document.querySelector('.my-button').click()
await fetch.mock.results[0].value; // delay for fetch()
await null; // another delay for res.json()expect(fetch).toBeCalledWith('/endpoint-that-returns-json')
expect(document.querySelector('.my-element')).toBeNull()
Post a Comment for "How To Test An Async Function In An Event Listener With Jest?"