2017-07-22 36 views
3

我有一個指令,突出文字:指令綁定不能在規範文件的工作

import { Directive, ElementRef, HostListener, Input } from '@angular/core'; 

@Directive({ selector: '[appHighlight]' }) 
export class HighlightDirective { 
    @Input('appHighlight') // tslint:disable-line no-input-rename 
    highlightColor: string; 

    constructor(private el: ElementRef) { } 

    @HostListener('mouseenter') 
    onMouseEnter() { 
    this.highlight(this.highlightColor || 'yellow'); 
    } 

    @HostListener('mouseleave') 
    onMouseLeave() { 
    this.highlight(null); 
    } 

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

在我的應用程序的HTML我有:

This <span [appHighlight]="'pink'">is nice</span>! 

和它的作品

hover text changes color

然後我開始構建一些測試,並且在一次測試中我嘗試綁定不同的顏色(只是li關於上述示例),但它不綁定該值,該字段爲undefined

import { ComponentFixture, TestBed } from '@angular/core/testing'; 

import { Component } from '@angular/core'; 
import { HighlightDirective } from './highlight.directive'; 

@Component({ 
    selector: 'app-test-container', 
    template: ` 
    <div> 
     <span id="red" appHighlight>red text</span> 
     <span id="green" [appHighlight]="'green'">green text</span> 
     <span id="no">no color</span> 
    </div> 
    ` 
}) 
class ContainerComponent { } 

const mouseEvents = { 
    get enter() { 
    const mouseenter = document.createEvent('MouseEvent'); 
    mouseenter.initEvent('mouseenter', true, true); 
    return mouseenter; 
    }, 
    get leave() { 
    const mouseleave = document.createEvent('MouseEvent'); 
    mouseleave.initEvent('mouseleave', true, true); 
    return mouseleave; 
    }, 
}; 

fdescribe('HighlightDirective',() => { 
    let fixture: ComponentFixture<ContainerComponent>; 
    let container: ContainerComponent; 
    let element: HTMLElement; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ContainerComponent, HighlightDirective], 
    }); 

    fixture = TestBed.createComponent(ContainerComponent); 
    container = fixture.componentInstance; 
    element = fixture.nativeElement; 
    }); 

    fit('should set background-color green when passing green parameter',() => { 
    const targetElement = <HTMLSpanElement>element.querySelector('#green'); 

    targetElement.dispatchEvent(mouseEvents.enter); 
    expect(targetElement.style.backgroundColor).toEqual('green'); 
    }); 
}); 

測試輸出顯示

fallback color

難道我做錯了什麼?爲什麼它不綁定顏色​​?

回答

1

我發現默認情況下,Angular在測試期間不會在模板上運行綁定。如Angular detectchanges documentation中所述,即使簡單的{{ myVar }}也不會運行,除非您使其運行綁定和生命週期事件。

有在這種情況下兩個選擇,我可以手動調用

fixture.detectChanges(); 

剛過,我得到我的夾具。

或者,我可以有一個供應商,將其設置爲自動運行的東西

providers: [ 
    { provide: ComponentFixtureAutoDetect, useValue: true }, 
],