Angular 2 fakeAsync在使用tick()的函数中等待超时? [英] Angular 2 fakeAsync waiting for timeout in a function using tick()?

查看:590
本文介绍了Angular 2 fakeAsync在使用tick()的函数中等待超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从Angular 2中的模拟后端获得单元测试的结果。目前,我们使用 fakeAsync 并使用超时来模拟时间的流逝。

I'm trying to get the results from a mock backend in Angular 2 for unit testing. Currently, we are using fakeAsync with a timeout to simulate the passing of time.

当前工作单位测试

it('timeout (fakeAsync/tick)', fakeAsync(() => {
    counter.getTimeout();
    tick(3000); //manually specify the waiting time
}));

但是,这意味着我们仅限于手动定义的超时。不是在异步任务完成时。我要做的是让 tick()等到任务完成后再继续测试。

But, this means that we are limited to a manually defined timeout. Not when the async task is completed. What I'm trying to do is getting tick() to wait until the task is completed before continuing with the test.

这似乎不按预期工作。

This does not seem to work as intended.

读取 fakeAsync 勾选答案此处解释说:


tick()模拟异步的时间流逝。

tick() simulates the asynchronous passage of time.

我设置了 plnkr示例模拟此场景。

I set up a plnkr example simulating this scenario.

这里,我们调用 getTimeout()方法,该方法调用具有超时的内部异步任务。在测试中,我们尝试包装它并在调用 getTimeout()方法后调用 tick()

Here, we call the getTimeout() method which calls an internal async task that has a timeout. In the test, we try wrapping it and calling tick() after calling the getTimeout() method.

counter.ts

getTimeout() {
  setTimeout(() => {
    console.log('timeout')
  },3000)
}

counter.specs.ts

it('timeout (fakeAsync/tick)', fakeAsync(() => {
    counter.getTimeout();
    tick();
}));

但是,单元测试失败并显示错误错误:1个计时器仍在队列中。

But, the unit test fails with the error "Error: 1 timer(s) still in the queue."

是否在此处发布角度回购与此有什么关系?

是否可以使用 tick()这种方式等待超时功能?或者我可以使用另一种方法吗?

Is it possible to use tick() this way to wait for a timeout function? Or is there another approach that I can use?

推荐答案

试试这个:

// I had to do this:
it('timeout (fakeAsync/tick)', (done) => {
  fixture.whenStable().then(() => {
       counter.getTimeout();
       tick();
    done();
  });
});

来源

这篇关于Angular 2 fakeAsync在使用tick()的函数中等待超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆