带有DOM操作的角度单元测试

时间:2020-03-27 01:45:32

标签: typescript unit-testing dom angular7 karma-jasmine

您好,我想寻求帮助来测试以下功能。我的方法是在测试用例中将tr分配给我的tagName,以测试其中的if条件。

我的TS文件中的功能是

  domEles : any;
  length : number = 0;

  moveToList(e : KeyboardEvent){
    if(document.activeElement.tagName.toLowerCase() == "tr"){
      this.domEles = document.querySelectorAll('#listTableBody > *');
      this.length = this.domEles.length;

      const activeEle = document.activeElement;
      const activeEleIndex = Array.prototype.indexOf.call(this.domEles, activeEle);

      if((e.key == "ArrowDown" || e.key == "Down") && activeEleIndex < this.length - 1 ) {
        const nextElem = <HTMLElement>activeEle.nextElementSibling;
        nextElem.focus();
      } 

      if((e.key == "ArrowUp" || e.key == "Up") && activeEleIndex > 0) {
        const prevElem = <HTMLElement>activeEle.previousElementSibling;
        prevElem.focus();
      }
      this.detector.detectChanges();
    }
  }

在我的SPEC文件中,方法是:

    it('should trigger moveToList function',()=>{

        let doc = (this as any).document.activeElement;
        doc.tagName = "tr"

        let nextElem = spyOn(doc.activeElement, 'nextElementSibling');
        component.length = 5;
        component.domEles = 1;
        const e = new KeyboardEvent('keydown', {key: 'ArrowDown'});

        component.moveToList(e);

        expect(nextElem).toHaveBeenCalled();

    });

在我执行测试并检查时,此测试未获取/触发moveToList函数中的if条件。 您能否在不修改函数中实际代码的情况下帮助我获得测试用例的最佳方法?预先感谢

0 个答案:

没有答案