我正在尝试为一段尝试执行的代码编写测试
它看起来像这样:
AA
假设if x.group(1) != x.group(2)
返回一个Promise,只有在调用// 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());
}
之后才能解决。理想情况下,我想编写这样的测试:
myFunction()
我知道Jest具有JSDOM环境,因此我能够很容易地测试第一种情况。但是,我无法弄清楚如何测试该行:
foo()
我知道有一个// 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)
method。但这仅告诉我已经调用了某种方法。它不允许我模拟文档尚未完成加载的状态,然后随后触发window.addEventListener("load", () => foo());
为“完成”。