在方法中使用 setTimeout 测试 Angular 组件

Test Angular Component with setTimeout in method

我正在尝试在 angular 组件中测试方法,如下所示:

  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 中的这两个函数都被调用?

How can I ensure that both of these functions within the setTimeout get called?

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

更多

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

function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms)
    })
}

并在instance.answerSelect({correct: true});

之后添加await sleep(2000)
  1. $timeout 服务注入到您的测试中。
  2. 使用 timeout.flush() 函数控制测试时间。

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