新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Angular教程:Angular測(cè)試管道
測(cè)試管道
你可以在沒(méi)有 Angular 測(cè)試工具的情況下測(cè)試管道。

如果你要試驗(yàn)本指南中所講的應(yīng)用,請(qǐng)?jiān)跒g覽器中運(yùn)行它或下載并在本地運(yùn)行它。
測(cè)試 TitleCasePipe
這個(gè)管道類有一個(gè)方法 ?transform?,它把輸入值變成一個(gè)轉(zhuǎn)換后的輸出值。?transform ?的實(shí)現(xiàn)很少會(huì)與 DOM 交互。除了 ?@Pipe? 元數(shù)據(jù)和一個(gè)接口之外,大多數(shù)管道都不依賴于 Angular。
考慮一個(gè) ?TitleCasePipe?,它會(huì)把每個(gè)單詞的第一個(gè)字母大寫。這里是通過(guò)正則表達(dá)式實(shí)現(xiàn)的。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'titlecase', pure: true})
/** Transform to Title Case: uppercase the first letter of the words in a string. */
export class TitleCasePipe implements PipeTransform {
transform(input: string): string {
return input.length === 0 ? '' :
input.replace(/\w\S*/g, (txt => txt[0].toUpperCase() + txt.slice(1).toLowerCase() ));
}
}任何使用正則表達(dá)式的東西都值得徹底測(cè)試。使用簡(jiǎn)單的 Jasmine 來(lái)探索預(yù)期的案例和邊緣情況。
describe('TitleCasePipe', () => {
// This pipe is a pure, stateless function so no need for BeforeEach
const pipe = new TitleCasePipe();
it('transforms "abc" to "Abc"', () => {
expect(pipe.transform('abc')).toBe('Abc');
});
it('transforms "abc def" to "Abc Def"', () => {
expect(pipe.transform('abc def')).toBe('Abc Def');
});
// ... more tests ...
});
編寫 DOM 測(cè)試來(lái)支持管道測(cè)試
這些都是對(duì)管道進(jìn)行隔離測(cè)試的。他們無(wú)法判斷當(dāng) ?TitleCasePipe ?應(yīng)用于組件中時(shí)是否能正常運(yùn)行。
考慮添加這樣的組件測(cè)試:
it('should convert hero name to Title Case', () => {
// get the name's input and display elements from the DOM
const hostElement: HTMLElement = fixture.nativeElement;
const nameInput: HTMLInputElement = hostElement.querySelector('input')!;
const nameDisplay: HTMLElement = hostElement.querySelector('span')!;
// simulate user entering a new name into the input box
nameInput.value = 'quick BROWN fOx';
// Dispatch a DOM event so that Angular learns of input value change.
nameInput.dispatchEvent(new Event('input'));
// Tell Angular to update the display binding through the title pipe
fixture.detectChanges();
expect(nameDisplay.textContent).toBe('Quick Brown Fox');
}); 網(wǎng)站名稱:創(chuàng)新互聯(lián)Angular教程:Angular測(cè)試管道
當(dāng)前網(wǎng)址:http://www.dlmjj.cn/article/cdhsojg.html


咨詢
建站咨詢
