首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Karma/Jasmine中测试点击

如何在Karma/Jasmine中测试点击
EN

Stack Overflow用户
提问于 2018-08-09 22:19:18
回答 1查看 1.4K关注 0票数 0

我在外部点击了我的指令:

代码语言:javascript
复制
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);
      }
  }
}

我可以做什么类型的测试来确定它是否正常工作?那我怎么测试呢?

它在组件中使用。例如,模态。当我在模式之外单击时,它会关闭。

EN

回答 1

Stack Overflow用户

发布于 2019-04-24 19:42:03

代码语言:javascript
复制
 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 - eleent进行测试时,这将会起作用,当你在外部点击时,你必须写的另一个条件,我不能写的properly.seems事件是不会发出的!

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51769438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档