如何以角度为 setTimeout 函数和 activeElement 编写单元测试?

时间:2021-03-15 10:05:30

标签: javascript angular unit-testing karma-jasmine angular-test

我想为以下函数编写单元测试用例:

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

1 个答案:

答案 0 :(得分:0)

可以使用fakeAsync,可以调用tick(500)来模拟时间的异步流逝 更多详情请点击https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync