【问题标题】:How to write unit test in angular for setTimeout function and activeElement?如何以角度为 setTimeout 函数和 activeElement 编写单元测试?
【发布时间】:2021-06-12 14:17:06
【问题描述】:

我想为下面的函数写一个单元测试用例:

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

我是角度单元测试的新手,从来没有遇到过我必须在函数中测试 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
      })
    }));

【问题讨论】:

  • 你应该提取setTimeOut中的函数并单独测试。
  • @KrishnaMohan 谢谢...但我已经测试过 onContinueClick 和 activeModal.close() 。你能证明你的建议吗?

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


【解决方案1】:

可以使用fakeAsync,也可以调用tick(500)来模拟时间的异步流逝 更多细节在这里https://angular.io/guide/testing-components-scenarios#async-test-with-fakeasync

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    相关资源
    最近更新 更多