使用Jest测试应该在document.readyState ===“ complete”之前运行的代码

时间:2018-12-06 07:51:14

标签: javascript unit-testing testing jestjs

我要做什么

我正在尝试为一段尝试执行的代码编写测试

  1. 如果文档准备就绪,则立即运行;否则,
  2. 在文档加载完成后运行。

它看起来像这样:

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()); 为“完成”。

0 个答案:

没有答案