首页 > 解决方案 > Angular 5 / Jasmine 2 测试 setTimeout 函数只有一次

问题描述

我的问题是我有这个功能:

    loopPingAPI() {
    this.pingAPI().then(
        success => {
            this.setConnected(true);
            this.stopPingAPI();

            return true;
        }, error => {
            this.setConnected(false);
            return true;
        });
    this.timer = setTimeout(() => this.loopPingAPI(), 5000);
}

有一个 setTimeout (函数每 5000 毫秒启动一次),我尝试像这样测试它:

      it('should not call the stopPingApi function', fakeAsync(() => {
            connectivityService.loopPingAPI();
            flushMicrotasks();
            expect(connectivityService.stopPingAPI).not.toHaveBeenCalled();
        }));

我有这个错误:

Error: 1 timer(s) still in the queue.

有没有办法只调用一次函数 loopPingApi() ,然后调用 stopPingApi() 函数(这个函数通过 clearTimeout(this.timer) 杀死 setTimeout )?

PS:使用tick()/flush() 代替flushMicroTasks() 具有相同的结果。

标签: angularunit-testingjasmine2.0

解决方案


推荐阅读