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

查看:19
本文介绍了测试一个包含 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+1ms,然后检查元素是否真的消失了.

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

2:使用 fakeAsync()tick() 来模拟测试中的时间 - tick() 将解决 setTimeout in原始的 close(),并且检查可能在 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)
  })
}))

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

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,也不需要将期望语句包装在 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天全站免登陆