【发布时间】:2017-12-28 14:37:14
【问题描述】:
我有一个突出显示文本的指令:
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>!
它有效
然后我开始构建一些测试,在一个测试中我尝试绑定不同的颜色(就像上面的示例一样),但它没有绑定值,字段是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');
});
});
测试输出显示
我做错了吗?为什么不绑定green颜色?
【问题讨论】:
标签: angular unit-testing angular-directive