【问题标题】:Angular2 testing with Jasmine, mouseenter/mouseleave-test使用 Jasmine 进行 Angular2 测试,mouseenter/mouseleave-test
【发布时间】:2016-10-30 08:52:58
【问题描述】:

我有一个 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()..

谢谢!

【问题讨论】:

    标签: unit-testing angular angular2-directives angular2-testing


    【解决方案1】:

    代替

    div.mouseenter();
    

    这应该可行:

    let event = new Event('mouseenter');
    div.dispatchEvent(event);
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-16
          • 2017-02-26
          • 2016-07-20
          • 2013-06-28
          • 1970-01-01
          • 1970-01-01
          • 2023-03-14
          • 2016-10-15
          相关资源
          最近更新 更多