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

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

this.showngIf是必然的.

this.animate绑定到动画.

我有一个测试需要测试这个功能

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()时,你如何正确地测试这个功能?

我用的是jasmine.clock().tick(251),但windows 永远不会消失.你对此也有什么 idea 吗?

推荐答案

你可以做两件事中的一件:

1:实际上在测试中等待250+setTimeout()毫秒,然后判断元素是否真的消失了.

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

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

服务

对于服务,您不需要在tick之后调用detectChanges,也不需要将expect语句包装在whenStable中.你可以在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();
  }));

Angular相关问答推荐

尽管有模拟间谍实现,规范文件仍调用真正的服务

CDK虚拟滚动由于组件具有注入属性而在滚动时看到错误的值

[已解决]如何在模块ngDoBootstrap中测试Angular 自定义元素和做覆盖

使用jsPDF生成带有图像的PDF时出现灰色条纹

Angular react 形式验证问题

MAT折叠面板的动态开启和关闭无法工作

以 Angular 形式添加动态控件失败

从具有特定 node 值的现有数组创建新数组

带有 Angular 2 的 Django

为什么 HttpParams 在 Angular 4.3 中的多行中不起作用

如何在插值中编写条件?

Angular2 测试 - 按 ID 获取元素

如何在 Angular 2 中获取与 ElementRef 关联的组件的引用

如何在 ngFor 循环中创建变量?

Angular2 + Jspm.io:使用类decorator 时需要反射元数据垫片

检测指令中输入值何时更改

如何使用 Angular 6 工作的 ngModel 创建自定义输入组件?

找不到模块angular2/core

在Angular2 Dart中设置路由和RouterLink的正确方法是什么

No provider for Router?