【问题标题】:Test Angular Component with setTimeout in method在方法中使用 setTimeout 测试 Angular 组件
【发布时间】:2018-02-19 08:58:33
【问题描述】:

我正在尝试在这样的角度组件中测试一种方法:

  answerSelect(answer: any): void {
    this.selectedAnswer = answer;

    // submit the answer
    setTimeout(() => {
      if (answer.correct) this.submit();
      this.selectedAnswer = undefined;
    }, 500);
  }

这是我目前所拥有的:

 describe('answerSelect()', () => {

      it('should set this.selectedAnswer = answer', async(() => {
        spyOn(instance, 'answerSelect').and.callThrough();
        instance.selectedAnswer = 'notTheAnswer';
        instance.answerSelect(('answer'));

        expect(instance.selectedAnswer).toBe('answer');
      }));

      it('should submit the answer', async(() => {
        spyOn(instance, 'answerSelect').and.callThrough();
        spyOn(instance, 'submit');
        instance.selectedAnswer = 'notTheAnswer';
        instance.answerSelect({correct: true});

        expect(instance.submit).toHaveBeenCalled();
        expect(instance.selectedAnswer).toBe(undefined);
      }));

  });

第一个测试 (should set this.selectedAnswer = answer) 按预期工作。

但是,由于setTimeout(),我似乎无法使第二个测试 (should submit the answer) 正常工作,并且出现以下两个错误:

1) Expected spy submit to have been called. 所以this.submit() 不会被调用。

2) Expected Object({ correct: true }) to be undefined. 所以this.selectedAnswer = undefined; 也不会被调用。

如何确保setTimeout 中的这两个函数都被调用?

【问题讨论】:

    标签: angular typescript asynchronous jasmine tdd


    【解决方案1】:
    1. $timeout 服务注入您的测试。
    2. 使用 timeout.flush() 函数控制测试中的时间。

    有关此类测试用例的示例,请参阅this spec

    【讨论】:

      【解决方案2】:
      function sleep(ms) {
          return new Promise(resolve => {
              setTimeout(resolve, ms)
          })
      }
      

      instance.answerSelect({correct: true});之后添加await sleep(2000)

      【讨论】:

        【解决方案3】:

        如何确保 setTimeout 中的这两个函数都被调用?

        在您的测试中添加延迟并确保您的测试也是异步的。

        更多

        结帐 jasmine 异步支持 https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

        【讨论】:

          猜你喜欢
          • 2020-11-19
          • 2022-01-15
          • 1970-01-01
          • 2016-12-06
          • 2021-09-25
          • 1970-01-01
          • 2014-02-09
          • 1970-01-01
          • 2018-07-22
          相关资源
          最近更新 更多