4

我有一個HighlightDirective如果鼠標進入的區域,像這也突出:Angular2測試茉莉,的mouseenter /鼠標離開測試

@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() { 
    } 
} 

現在,我已經得到了消息:

失敗:div.mouseenter不是一個函數

那麼,有誰知道,這是正確的功能(如果存在)?我已經嘗試使用click()..

謝謝!

回答

9

而不是

div.mouseenter(); 

這應該工作:

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

它的工作原理,謝謝! – bene

+0

很高興聽到:) –