Angular 集成测试:如何在 MouseEvent 上指定目标

Angular integration testing: how to specify the target on a MouseEvent

我试图通过在 HTML 元素之一上使用 "triggerEventHandler" 在我的集成测试中调用点击事件。我希望事件的 "target" 属性 由 "triggerEventHandler" 设置。那没有发生。当我执行测试时,控制台中记录了以下错误:“Cannot read 属性 'tagName' of null”,当我尝试获取 tagName 时会发生这种情况目标元素的。

我应该如何实施这个测试?

查看

<h1 class="h1-class" (click)="click($event)" (contextmenu)="rightClick($event)">H1</h1>
<h2 class="h2-class" (click)="click($event)" (contextmenu)="rightClick($event)">H2</h2>

组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'biq-dbg',
  templateUrl: './biq-dbg.component.html',
  styleUrls: ['./biq-dbg.component.less']
})

export class BiqDbgComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

  click(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == "h1")
      console.log("H1 was clicked");
    if (targetElement.tagName.toLocaleLowerCase() == "h2")
      console.log("H2 was clicked");
  }

  rightClick(event: MouseEvent) {
    console.log(event);
    let targetElement = event.target as HTMLElement;
    if (targetElement.tagName.toLocaleLowerCase() == "h1")
      console.log("H1 was right-clicked");
    if (targetElement.tagName.toLocaleLowerCase() == "h2")
      console.log("H2 was right-clicked");
  }
}

规格

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'

import { BiqDbgComponent } from './biq-dbg.component';

fdescribe('BiqDbgComponent', () => {
  let component: BiqDbgComponent;
  let fixture: ComponentFixture<BiqDbgComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BiqDbgComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BiqDbgComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('h1 should react to click', () => {
    let h1 = fixture.debugElement.query(By.css(".h1-class"));
    let mouseEvent: MouseEvent = new MouseEvent("click", { clientX: 10, clientY: 20, button: 0});

    h1.triggerEventHandler("click", mouseEvent);
    fixture.detectChanges();
  })

  fit('h1 should react to right-click', () => {
    let h1 = fixture.debugElement.query(By.css(".h1-class"));
    let mouseEvent: MouseEvent = new MouseEvent("contextmenu", { clientX: 10, clientY: 20, button: 2});

    h1.triggerEventHandler("contextmenu", mouseEvent);
    fixture.detectChanges();
  })
});

"triggerEventHandler" ,所做的只是为给定的事件名称调用所有侦听器。

为了模拟真实事件,例如鼠标单击或鼠标右键单击,您必须使用 "dispatchEvent(event)":How to simulate a mouse click using javascript