屬性型指令的單元測(cè)試
- 這里依然用文本高亮的指令來說明。
import { Directive, ElementRef, Input, OnChanges, Renderer } from '@angular/core';
@Directive({ selector: '[highlight]' })
export class HighlightDirective implements OnChanges {
defaultColor = 'rgb(211, 211, 211)'; // lightgray
@Input('highlight') bgColor: string;
constructor(private renderer: Renderer, private el: ElementRef) {
renderer.setElementProperty(el.nativeElement, 'customProperty', true); /** set the element's customProperty to true */
}
ngOnChanges() {
this.renderer.setElementStyle(
this.el.nativeElement, 'backgroundColor',
this.bgColor || this.defaultColor );
}
}
- 單一的單元測(cè)試
import { Component } from '@angular/core';
@Component({
template: `
<h2 highlight="skyblue">About</h2>
<twain-quote></twain-quote>
<p>All about this sample</p>`
})
export class AboutComponent { }
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [ AboutComponent, HighlightDirective],
schemas: [ NO_ERRORS_SCHEMA ] //用來“淺化”組件測(cè)試程序,告訴編譯器忽略不認(rèn)識(shí)的元素和屬性,這樣你不再需要聲明無關(guān)的組件和指令,
})
.createComponent(AboutComponent);
fixture.detectChanges(); // initial binding
});
it('should have skyblue <h2>', () => {
const de = fixture.debugElement.query(By.css('h2'));
expect(de.styles['backgroundColor']).toBe('skyblue');
});
但是測(cè)試單一的用例無法探索該指令的全部能力。但是查找和測(cè)試所有使用該指令的組件非常繁瑣和脆弱,并且通常無法覆蓋所有組件,此時(shí)我們可以創(chuàng)建一個(gè)展示所有使用該指令的人工測(cè)試組件。
@Component({
template: `
<h2 highlight="yellow">Something Yellow</h2>
<h2 highlight>The Default (Gray)</h2>
<h2>No Highlight</h2>
<input #box [highlight]="box.value" value="cyan"/>`
})
class TestComponent { }
beforeEach(() => {
fixture = TestBed.configureTestingModule({
declarations: [ HighlightDirective, TestComponent ] //這里要把指令和人工組件都聲明一下
})
.createComponent(TestComponent);
fixture.detectChanges();
/** 查找所有用到該指令的宿主元素 */
des = fixture.debugElement.queryAll(By.directive(HighlightDirective));
bareH2 = fixture.debugElement.query(By.css('h2:not([highlight])')); //沒有用到該指令的宿主元素});
it('should have three highlighted elements', () => {
expect(des.length).toBe(3);
});
it('should color 1st <h2> background "yellow"', () => {
expect(des[0].styles['backgroundColor']).toBe('yellow');
});
it('should color 2nd <h2> background w/ default color', () => {
const dir = des[1].injector.get(HighlightDirective) as HighlightDirective; //監(jiān)聽指令屬性變化
expect(des[1].styles['backgroundColor']).toBe(dir.defaultColor);
});
it('should bind <input> background to value color', () => {
// easier to work with nativeElement
const input = des[2].nativeElement as HTMLInputElement;
expect(input.style.backgroundColor).toBe('cyan', 'initial backgroundColor');
// dispatch a DOM event so that Angular responds to the input value change.
input.value = 'green';
input.dispatchEvent(newEvent('input'));
fixture.detectChanges();
expect(input.style.backgroundColor).toBe('green', 'changed backgroundColor');
});
// customProperty tests
it('all highlighted elements should have a true customProperty', () => {
const allTrue = des.map(de => !!de.properties['customProperty']).every(v => v === true);
expect(allTrue).toBe(true);
});
it('bare <h2> should not have a customProperty', () => {
expect(bareH2.properties['customProperty']).toBeUndefined();
});
- 已知元素類型時(shí),By.directive是一種獲取擁有這個(gè)指令的元素的好辦法;
- Angular將指令添加到它的元素的注入器中。 默認(rèn)顏色的測(cè)試程序使用第二個(gè)
<h2>的注入器來獲取它的HighlightDirective實(shí)例以及它的defaultColor。 - DebugElement.properties提供了對(duì)指令的自定義屬性的訪問。
ps:自己在處理這塊兒?jiǎn)卧獪y(cè)試時(shí)遇到最大的坑就是無法監(jiān)聽屬性值的變化以及獲取到的DOM元素一直有問題(獲取時(shí)機(jī)不對(duì)),花了很多時(shí)間。