加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 使用Jasmine进行Angular2测试,mouseenter / mousele

发布时间:2020-12-17 06:56:35 所属栏目:安全 来源:网络整理
导读:我有一个HighlightDirective,如果鼠标进入某个区域会突出显示,如: @Directive({ selector: '[myHighlight]',host: { '(mouseenter)': 'onMouseEnter()','(mouseleave)': 'onMouseLeave()' }})export class HighlightDirective { private _defaultColor = 'G
我有一个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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读