问题描述
我想为以下函数编写单元测试用例:
onfactorblur():void{
var that=this;
setTimeout(function(){
var target=document.activeElement;
if(target.tagName=="BUTTON"){
if(target.textContent=="CONTINUE"){
that.onContinueClick();
}
else{
that.activeModal.close();
}
}
},.5);
}
我是 Angular 单元测试的新手,从来没有遇到过我必须在函数内测试 setTimeout 的情况。我试过了:
it('Should close the modal if target element is button',fakeAsync(()=>{
spyOn(component,'onContinueClick');
spyOn(component.activeModal,'close');
tick(1);
fixture.detectChanges();
fixture.whenStable().then(()=>{
//What should I write here
})
}));
解决方法
可以使用fakeAsync
,可以调用tick(500)
来模拟时间的异步流逝
更多详情请点击https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync