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})未定义。
sothis.selectedAnswer=undefined代码>也不会被调用
如何确保调用setTimeout
中的这两个函数
如何确保调用setTimeout中的这两个函数
在测试中添加延迟,并确保测试也是异步的
更多
签出jasmine异步支持
并在instance.answerSelect({correct:true})之后添加wait sleep(2000)
代码>
将服务注入到测试中
使用timeout.flush()函数控制测试中的时间
有关此类测试用例的示例,请参阅
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}