我试图在角度组件中测试方法,如下所示:
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
)按预期工作。
但是,我似乎无法通过should submit the answer
进行第二次测试(setTimeout()
),并且遇到以下两个错误:
1)Expected spy submit to have been called.
因此this.submit()
无法被调用。
和
2)Expected Object({ correct: true }) to be undefined.
因此this.selectedAnswer = undefined;
也无法被调用。
如何确保调用setTimeout
中的这两个函数?
答案 0 :(得分:0)
如何确保调用setTimeout中的这两个函数?
在测试中添加延迟并确保您的测试也是异步的。
结帐jasmine异步支持https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support
答案 1 :(得分:0)
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
并在await sleep(2000)
instance.answerSelect({correct: true});
答案 2 :(得分:-1)