微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试 – 使用Jasmine进行Angular2测试,mouseenter / mouseleave-test

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

使用testclass:

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

现在,我收到了消息:

Failed: div.mouseenter is not a function

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

谢谢!

解决方法

代替

div.mouseenter();

这应该工作:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐