【问题标题】:Angular Unit Test Using SetInterval使用 SetInterval 的角度单元测试
【发布时间】:2021-07-09 10:00:30
【问题描述】:

我不明白如何为 setInterval 编写单元测试。我在 .component.ts 中有这样的功能

startTimer() {
this.showResend = false;
this.otpError = false;
this.time = 60;
this.interval = setInterval(() => {
  this.time--;
  if (this.time < 1) {
    this.endTimer();
  }
}, 1000);

}

我设置的区间变量与变量时间相同,代码如下所示

      it('start timer function', () => {
      component.startTimer();
      expect(component.showResend).toBeFalsy();
      expect(component.otpError).toBeFalsy()
      expect(component.time).toEqual(60);
      expect(component.interval).toEqual(60)
      })

但在区间值总是在变化。你能帮我如何正确编写代码吗?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    您需要在fakeAsynce 区域中运行测试并使用tick():

     it('start timer function', fakeAsync(() => {
          component.startTimer();
          expect(component.showResend).toBeFalsy();
          expect(component.otpError).toBeFalsy();
          tick(1000); // After this you need to call detectChanges()
          expect(component.time).toEqual(59);
          }));
    

    为了更好地测试它,参数化 startTimer() 如下:

    startTimer(time: number) {
    this.showResend = false;
    this.otpError = false;
    this.interval = setInterval(() => {
      time--;
      if (this.time < 1) {
        this.endTimer();
      }
    }, 1000);
    

    然后在你的测试中:

    it('start timer function', fakeAsync(() => {
          const time = 2;
          component.startTimer(time);
          expect(component.showResend).toBeFalsy();
          expect(component.otpError).toBeFalsy();
          tick(1000); // After this you need to call detectChanges()
          expect(component.time).toEqual(time - 1);
     }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多