如何测试Karma / Jasmine外部的点击

问题描述 投票:0回答:1

我的指令点击外面:

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);
      }
  }
}

我可以做些什么类型的测试来确定它是否有效?我该怎么测试?

它用在组件中。例如模态。当我点击模态之外它关闭。

angular unit-testing karma-jasmine angular6
1个回答
-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元素时进行测试时,这将有效。当你在外面点击时你需要写的另一个条件,我无法正确写入。看不到事件的事件!

© www.soinside.com 2019 - 2024. All rights reserved.