Angular - Jasmine - 如何在间隔内测试动作

Angular - Jasmine - How to test an action inside an interval

我想用 jasmine 测试以下方法:

  public init(): Subscription {
    return interval(100).subscribe(() => this.doSomething())
  }

我想测试调用 init 函数时执行的方法 doSomething。我发现了方法 doSomething.

我尝试了以下测试:

it('interval should call doSomething', () => {
    const mySpy: jasmine.Spy = spyOn<any>(service, 'doSomething');
    subs.push(service.init());
    expect(mySpy).toHaveBeenCalled();
  });

或者那个:

it('interval should call doSomething', fakeAsync(() => {
    const mySpy: jasmine.Spy = spyOn<any>(service, 'doSomething');
    subs.push(service.init());
    tick(200)
    expect(mySpy).toHaveBeenCalled();
  }));

对于第二次测试,我收到以下错误:Error: 1 periodic timer(s) still in the queue.

如何从测试中触发间隔,或者如何等待间隔执行?

添加

discardPeriodicTasks();

如你所愿。