为什么当我想在 Angular 中的 Jasmine&Karma 一段时间后检查预期结果时出现错误?

问题描述 投票:0回答:1

我想测试这个组件

describe('Test for check if window dissapeard', () => {
    let component: DismissMockedComponent;
    let fixture: ComponentFixture<DismissMockedComponent>;
  
    beforeEach(() => {
      fixture = TestBed.createComponent(DismissMockedComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('Check if window dissapeard after dissmiss time', () => {
      let delayTime = 3000;
      spyOn(component, "onAfterDelayTime");
  
      component.dismissible = true;
      component.dismissTimer = delayTime;
      fixture.detectChanges();
  
      setTimeout(() => {
        fixture.detectChanges();
        expect(component.onAfterDelayTime).toHaveBeenCalled();
      }, delayTime); 
    });
  });

和非常简单的模拟组件


  @Component({
    template: '<my-inform-window (afterDelayTime)="onAfterDelayTime()"></my-inform-window>'
  })
  class DismissMockedComponent {
    delayTime: number;

    onAfterDelayTime(){
        console.log('this function was triggered after delay time')
    }
  }

我收到一个错误

Async function did not complete within 5000ms

我会补充一点,当我将解雇时间设置为 1000 毫秒或 2000 毫秒时,所有工作都正确......

知道问题出在哪里吗?

angular karma-jasmine angular-test
1个回答
0
投票

使用 FakeAsync 测试时间延迟功能

  it('Check if window disappeared after dismiss time', fakeAsync(() => {
    const delayTime = 3000;
    spyOn(component, "onAfterDelayTime");

    component.dismissible = true;
    component.dismissTimer = delayTime;
    fixture.detectChanges();

    tick(delayTime); // Simulate the passage of delayTime milliseconds

    fixture.detectChanges();
    expect(component.onAfterDelayTime).toHaveBeenCalled();

    flush(); // Ensure that no more tasks are left in the queue
  }));
© www.soinside.com 2019 - 2024. All rights reserved.