所以我试着为我的库写一些单元测试。但是当运行jest时,我得到了可怕的结果:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't
stopped in your tests. Consider running Jest with `--detectOpenHandles`
to troubleshoot this issue.
我已经追踪到了我写的一个特定的类,它有一个静态构造函数块。在那个块中,我启动了一个setInterval
,或者一个setTimeout
函数。无论是哪种方式,我都尝试了同样的方式。
我知道Javascript没有析构函数是因为一些未知的原因(GC不是一个有效的原因。许多带有GC的语言都有析构函数)。当代码准备关闭时,我如何清理并停止setInterval
?
方案一:
class A {
static #blink = false;
static #blinker;
static {
A.#blinker = setInterval(() => {
A.#blink = !A.#blink;
}, 500);
}
}
备选方案二:
class B {
static #blink = false;
static #blinker = null;
static {
B.#doBlink();
}
static #doBlink() {
B.#blink = !B.#blink;
#blinker = setTimeout(() => B.#doBlink(), 500);
}
}
1条答案
按热度按时间pvcm50d11#
有多种选择:
1.向对象添加一个
.shutdown()
或.close()
方法,并在处理完对象并希望计时器停止时调用该方法。1.在计时器上调用
.unref()
,它们就不会阻止nodejs自然关闭--当nodejs事件循环检测是否有任何东西仍在运行时,它们不会被视为未完成的异步操作。1.使用代码的逻辑(您没有显示),计算出何时不再需要定时器,并根据这些条件自然地关闭
setTimeout()
或setInterval()
。