我的指令在外部单击:
import { Directive, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) { }
@Output()
public clickOutside = new EventEmitter();
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}
我可以进行哪些类型的测试以查看其是否有效?我该如何测试?
在组件中使用。例如模态。当我在模态之外单击时,它将关闭。
答案 0 :(得分:-1)
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Component } from '@angular/core';
import { ClickOutsideDirective } from '../p6-click-outside.directive';
@Component({
template: `<div (clickOutside)='onClick($event)' clickOutside> Click Outside this </div>
<button>This is outside<button>`
})
class TestClickOutsideComponent {
public active: boolean = false;
onClick() {
this.active = !this.active;
}
}
fdescribe('P6ClickOutsideDirective', () => {
let component: TestClickOutsideComponent;
let fixture: ComponentFixture<TestClickOutsideComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ClickOutsideDirective, TestClickOutsideComponent]
});
fixture = TestBed.createComponent(TestClickOutsideComponent);
component = fixture.componentInstance;
});
fit('should create component', () => {
expect(component).toBeDefined();
});
fit('it should call onClick method when clicked on the div element', async(() => {
const activeValueBeforeClick = component.active;
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const div: HTMLElement = debugEl.querySelector('div');
div.click();
fixture.detectChanges();
expect(activeValueBeforeClick).toBe(component.active);
这将在您单击div进行测试时起作用,在外部单击时还必须编写一个条件,我无法正确编写。似乎没有发出事件!