测试包含setTimeout()的函数 [英] Test a function that contains a setTimeout()

查看:95
本文介绍了测试包含setTimeout()的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中有一个关闭函数,其中包含一个setTimeout(),以便为动画完成留出时间.

I have a close function in my component that contains a setTimeout() in order to give time for the animation to complete.

public close() {
    this.animate = "inactive"
    setTimeout(() => {
       this.show = false
    }, 250)
}

this.show绑定到ngIf.

this.animate绑定到动画.

我有一个需要测试此功能的测试

I have a test that needs to test this function

it("tests the exit button click", () => {
  comp.close()
  fixture.detectChanges()
  //verifies the element is no longer in the DOM
  const popUpWindow = fixture.debugElement.query(By.css("#popup-window"))
  expect(popUpWindow).toEqual(null)
})

出现setTimeout()时,如何正确测试此功能?

How do you properly test this function when there is a setTimeout()?

我正在使用jasmine.clock().tick(251),但是窗口永远不会消失.还有什么想法吗?

I was using jasmine.clock().tick(251) but the window would never disappear. any thoughts on this as well?

推荐答案

您可以执行以下两项操作之一:

You could do one of two things:

1:实际上是在setTimeout()中等待250 + 1 ms的测试,然后检查该元素是否真正消失了.

1: Actually wait in the test 250+1 ms in a setTimeout(), then check if the element actually disappeared.

2:使用fakeAsync()tick()在测试中模拟时间-tick()将解决原始close()中的setTimeout,并且检查可能会在fixture.whenStable().then(...)之后进行.

2: use fakeAsync() and tick() to simulate time in the test - a tick() will resolve the setTimeout in the original close(), and the check could happen right after in a fixture.whenStable().then(...).

例如:

it("tests the exit button click", fakeAsync(() => {
  comp.close()
  tick(500)
  fixture.detectChanges()

  fixture.whenStable().then(() => {
    const popUpWindow = fixture.debugElement.query(By.css("#popup-window"))
    expect(popUpWindow).toBe(null)
  })
}))

我建议使用第二种方法,因为它比实际等待原始方法要快得多.如果您仍使用1st,请尝试降低测试前的超时时间,以使其运行更快.

I suggest using the 2nd one, as it is much more faster than actually waiting for the original method. If you still use the 1st, try lowering the timeout time before the test to make the it run faster.

服务

对于服务,您不需要在tick之后调用detectChanges,也不需要将Expect语句包装在whenStable中.您可以在tick之后立即执行逻辑.

For services you do not need to call detectChanges after tick and do not need to wrap the expect statements within whenStable. you can do your logic right after tick.

  it('should reresh token after interval', fakeAsync(() => {
    // given
    const service: any = TestBed.get(CognitoService);
    const spy = spyOn(service, 'refreshToken').and.callThrough();
    ....
    // when
    service.scheduleTokenRefresh();
    tick(TOKEN_REFRESH_INTERVAL);
    // then
    expect(spy).toHaveBeenCalled();
  }));

这篇关于测试包含setTimeout()的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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