測試管道
Testing Pipes
你可以在沒有 Angular 測試工具的情況下測試管道。
You can test pipes without the Angular testing utilities.
對於本測試指南中描述的範例應用,參閱
For the sample app that the testing guides describe, see the
要了解本測試指南中涉及的測試特性,請參閱
For the tests features in the testing guides, see
測試 TitleCasePipe
Testing the TitleCasePipe
這個管道類別有一個方法 transform
,它把輸入值變成一個轉換後的輸出值。 transform
的實現很少會與 DOM 互動。除了 @Pipe
元資料和一個介面之外,大多數管道都不依賴於 Angular。
A pipe class has one method, transform
, that manipulates the input value into a transformed output value. The transform
implementation rarely interacts with the DOM. Most pipes have no dependence on Angular other than the @Pipe
metadata and an interface.
考慮一個 TitleCasePipe
,它會把每個單詞的第一個字母大寫。這裡是透過正則表示式實現的。
Consider a TitleCasePipe
that capitalizes the first letter of each word. Here's an implementation with a regular expression.
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.substr(1).toLowerCase() ));
}
}
任何使用正則表示式的東西都值得徹底測試。使用簡單的 Jasmine 來探索預期的案例和邊緣情況。
Anything that uses a regular expression is worth testing thoroughly. Use simple Jasmine to explore the expected cases and the edge cases.
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 測試來支援管道測試
Writing DOM tests to support a pipe test
這些都是對管道進行隔離測試的。他們無法判斷當 TitleCasePipe
應用於元件中時是否能正常執行。
These are tests of the pipe in isolation. They can't tell if the TitleCasePipe
is working properly as applied in the application components.
考慮新增這樣的元件測試:
Consider adding component tests such as this one:
it('should convert hero name to Title Case', () => {
// get the name's input and display elements from the DOM
const hostElement = 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.
// In older browsers, such as IE, you might need a CustomEvent instead. See
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill
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');
});