2017-07-22 8 views
3

で働いていないバインディング私はテキストをハイライトディレクティブ持っている:私は私のアプリのHTMLで指令はspecファイル

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; 
    } 
} 

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

をそして、それは

hover text changes color

の作品

その後、私はいくつかのテストを構築し始めました。あるテストでは、別の色をバインドしようとしています上記の例のように)、値はバインドされません。フィールドは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はテスト中にテンプレートに対してバインディングを実行しないことを発見しました。 {{ myVar }}でも、Angular detectchanges documentationで説明されているように、バインディングとライフサイクルイベントを実行するまでは機能しません。このシナリオでは2つのオプションがあります

、私は手動で私は私のフィクスチャを取得した直後

fixture.detectChanges(); 

を呼び出すことができます。

または私はそれが

providers: [ 
    { provide: ComponentFixtureAutoDetect, useValue: true }, 
], 
自動的に物事を実行するように設定し、プロバイダを含むことができ、