angular - 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() 具有相同的结果。
解决方案
推荐阅读
- asp.net - ASP.NET Core API 中的递归映射 - 树结构
- laravel - Swagger 在 Heroku 上使用 HTTP,而不是 HTTPS
- javascript - 如何允许客户端从 Node.js + Express 服务器访问任何静态文件?
- android - 为什么我的回收站视图没有显示任何内容
- java - 将 long 转换为二进制然后将二进制字符串连接为 long 时出现运行时异常
- python - 裁剪 X 射线图像以移除黑色背景
- bash - 为什么它说整数预期?
- bash - 如何在 Bash 脚本中将部分文件名替换为其父目录的名称?
- flutter-animation - Flutter:如何将图像文件传递到另一个屏幕
- javascript - 如何在浏览器的本地存储中存储多个数据