What I'm trying to do
I am trying to write tests for a piece of code that tries to
- run immediately if the document is ready, or otherwise;
- run when the document has finished loading.
It looks something like this:
// this is inside a function that returns a Promise
// and it resolves when `foo()` is called
if (document.readyState === "complete") {
foo()
} else {
window.addEventListener("load", () => foo());
}
Assuming myFunction()
returns a Promise that is only resolved after foo()
is called. Ideally, I'd want to write a test like this:
// put the document in "loading" mode
document.readyState = "loading"
// use a flag to keep track of whether promise has resolved
let complete = false
myFunction().then(() => complete = true)
// check to see that promise has not resolved yet
expect(complete).toBe(false)
// trigger load event and then check to see that the promise is complete
document.triggerLoadEvent()
expect(complete).toBe(true)
What I've tried
I know that Jest has a JSDOM environment, so I'm able to test the first case pretty easily. However, I haven't been able to figure out how to test the line:
window.addEventListener("load", () => foo());
I know that there's a jest.spyOn
method. But that only tells me that a certain method has been called. It doesn't allow me to simulate the state in which the document has not yet finished loading, and then subsequently trigger the readyState
to be "complete".