我要测试点击外部指令。该扩展名是我在单击外部时忽略div元素。
import { Directive, ElementRef, Output, EventEmitter, HostListener } from
'@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {
}
@Output()
public clickOutside = new EventEmitter<HTMLElement>();
@HostListener('document:click', ['$event.target'])
public onClick(targetElement: HTMLElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
const doctorDropdown = document.getElementById('doctor-dropdown-list');
if (!clickedInside && !doctorDropdown.contains(targetElement)) {
this.clickOutside.emit(targetElement);
}
}
}
我无法测试这部分!
@HostListener('document:click', ['$event.target'])
public onClick(targetElement: HTMLElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
const doctorDropdown = document.getElementById('doctor-dropdown-list');
if (!clickedInside && !doctorDropdown.contains(targetElement)) {
this.clickOutside.emit(targetElement);
}
答案 0 :(得分:0)
import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ClickOutsideDirective } from '../click-outside.directive';
import { By } from '@angular/platform-browser';
@Component({
template: `
<div class="inside" (clickOutside)="clickOutside()"></div> // or doctor-dropdown-list
<div class="outside"></div>
`
})
class TestComponent {
clickOutside(): void{}
}
describe('ClickOutsideDirective', () => {
let fixture: ComponentFixture<TestComponent>;
let component: TestComponent;
let element: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ClickOutsideDirective, TestComponent],
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should create directive', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should trigger click inside', () => {
spyOn(component, 'clickOutside');
fixture.detectChanges();
const inside = fixture.debugElement.query(By.css('.inside')).nativeElement;
inside.click();
expect(component.clickOutside).not.toHaveBeenCalled();
});
it('should trigger click outside', () => {
spyOn(component, 'clickOutside');
fixture.detectChanges();
const outside = fixture.debugElement.query(By.css('.outside')).nativeElement;
outside.click();
expect(component.clickOutside).toHaveBeenCalled();
});
});