2017-07-22 16 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 }, 
],