无法在单元测试用例中调用@HostListener方法

时间:2018-01-10 18:47:47

标签: angular unit-testing jasmine angular-directive

我使用@Directive创建了一个自定义指令,其中我使用的是@HostListener,代码工作正常。
现在,在编写测试用例时,我需要从单元测试用例中调用@HostListener方法。此外,我可以看到代码覆盖范围内的代码未被覆盖 以下是代码:

focus-encapsulation.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appFocusEncapsulation]'
})
export class FocusEncapsulationDirective {

  constructor(private el: ElementRef) { }

  @HostListener('keydown', ['$event'])
  keyDown(event: Event) {
    console.log('event : ', event);
    event.preventDefault();
  }

}

对焦encapsulation.directive.spec.ts

import { FocusEncapsulationDirective } from './focus-encapsulation.directive';
import { Component, ElementRef, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from "@angular/platform-browser";

@Component({
  template: `<div appFocusEncapsulation><button type="button" (click)="add()">ADD</button></div>`
})
class TestHoverFocusComponent {
  constructor(private el: ElementRef) { 
    console.log('in constructor')
  }
}

fdescribe('FocusEncapsulationDirective', () => {

  let component: TestHoverFocusComponent;
  let fixture: ComponentFixture<TestHoverFocusComponent>;
  let inputEl: DebugElement;
  let elementRef: ElementRef

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestHoverFocusComponent, FocusEncapsulationDirective]
    });
    fixture = TestBed.createComponent(TestHoverFocusComponent);
    component = fixture.componentInstance;
    elementRef = fixture.nativeElement;
    inputEl = fixture.debugElement.query(By.css('button'));
  });

  it('should create an instance', () => {
    const directive = new FocusEncapsulationDirective(elementRef)
    expect(directive).toBeTruthy();
  });

  it('Focus over elements', () => {
    fixture.detectChanges();
    const event = {
      which : 9,
      keyCode : 9,
      srcElement :{
        innerText : 'ADD'
      },
      preventDefault: function() {
        console.log('preventDefault() method called');
      }
    }
    spyOn(event, 'preventDefault');
    inputEl.triggerEventHandler('keydown', event);
    expect(event.preventDefault()).toHaveBeenCalled();
  });

});

您可以在下面看到代码覆盖率报告:
enter image description here

这里我需要覆盖代码并获得此方法所需的正确测试用例。感谢。

1 个答案:

答案 0 :(得分:4)

以下是您的测试的固定版本:

fdescribe('FocusEncapsulationDirective', () => {

  let fixture: ComponentFixture<TestHoverFocusComponent>;
  let inputEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestHoverFocusComponent, FocusEncapsulationDirective]
    });
    fixture = TestBed.createComponent(TestHoverFocusComponent);
    inputEl = fixture.nativeElement.querySelector('button');
  });

  it('Focus over elements', () => {
    fixture.detectChanges();
    const event = new Event('keydown', { bubbles: true });
    spyOn(event, 'preventDefault');
    inputEl.dispatchEvent(event);
    expect(event.preventDefault).toHaveBeenCalled();
  });

});

关键点:

  • 你需要将spied函数本身传递给expect(),以检查它是否已被调用。你的代码调用 spied函数,并将它返回的内容传递给epect()。
  • 你需要传递一个实际的事件(特别是那个将bubbles标志设置为true的事件,否则事件不会起泡,并且封闭的div上的监听器将不会通知在封闭按钮上触发的事件)到本机DOM元素。