5

我有一个 HighlightDirective,如果鼠标进入一个区域,它会突出显示,例如:

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'Gainsboro';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

  private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

现在我想测试是否在事件中调用了(正确的)方法。所以是这样的:

  it('Check if item will be highlighted', inject( [TestComponentBuilder], (_tcb: TestComponentBuilder) => {
    return _tcb
      .createAsync(TestHighlight)
      .then( (fixture) => {
        fixture.detectChanges();
        let element = fixture.nativeElement;
        let component = fixture.componentInstance;
        spyOn(component, 'onMouseEnter');
        let div = element.querySelector('div');


        div.mouseenter();


        expect(component.onMouseEnter).toHaveBeenCalled();
      });
  }));

使用测试类:

@Component({
  template: `<div myHighlight (mouseenter)='onMouseEnter()' (mouseleave)='onMouseLeave()'></div>`,
  directives: [HighlightDirective]
})
class TestHighlight {
  onMouseEnter() {
  }
  onMouseLeave() {
  }
}

现在,我得到了消息:

失败:div.mouseenter 不是函数

那么,有谁知道,哪个是正确的功能(如果存在)?我已经尝试过使用 click() ..

谢谢!

4

3 回答 3

20

代替

div.mouseenter();

这应该工作:

let event = new Event('mouseenter');
div.dispatchEvent(event);
于 2016-06-28T08:42:56.923 回答
0

gunter 回答的附加信息,您需要向事件发送附加参数。否则不会触发。参考:https ://developer.mozilla.org/en-US/docs/Web/API/Event/composed

让 event = new Event('mouseenter', {composed: true}); 将是为 HTMLElement 定义事件以调用事件的正确方法。

于 2020-06-17T16:12:24.680 回答
0

此外,我还错过了 create 组件中的以下内容:

fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();  // <<< THIS

如果你这样做,它看起来就像测试正在工作,但是通过使用覆盖,你会发现事件没有被触发。一个令人讨厌的问题。

于 2020-10-16T09:58:04.733 回答