我使用@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();
});
});
这里我需要覆盖代码并获得此方法所需的正确测试用例。感谢。
答案 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();
});
});
关键点:
bubbles
标志设置为true的事件,否则事件不会起泡,并且封闭的div
上的监听器将不会通知在封闭按钮上触发的事件)到本机DOM元素。