Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 使用setTimeout in方法测试角度组件_Angular_Typescript_Asynchronous_Jasmine_Tdd - Fatal编程技术网

Angular 使用setTimeout in方法测试角度组件

Angular 使用setTimeout in方法测试角度组件,angular,typescript,asynchronous,jasmine,tdd,Angular,Typescript,Asynchronous,Jasmine,Tdd,我试图在一个角度分量中测试一种方法,如下所示: answerSelect(answer: any): void { this.selectedAnswer = answer; // submit the answer setTimeout(() => { if (answer.correct) this.submit(); this.selectedAnswer = undefined; }, 500); } 这就是我到目

我试图在一个角度分量中测试一种方法,如下所示:

  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);
      }));

  });
第一个测试(
应设置此选项。selectedAnswer=answer
)按预期工作

但是,由于
setTimeout()
的原因,我似乎无法让第二个测试(
应该提交答案)正常工作,我收到了以下两个错误:

1)
预期spy submit已被调用。
因此
此.submit()
未被调用

2)
预期对象({correct:true})未定义。
so
this.selectedAnswer=undefined也不会被调用

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

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

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

更多 签出jasmine异步支持

并在
instance.answerSelect({correct:true})之后添加
wait sleep(2000)

  • 将服务注入到测试中
  • 使用timeout.flush()函数控制测试中的时间
  • 有关此类测试用例的示例,请参阅

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