{ "id": "guide/testing-pipes", "title": "Testing Pipes", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Testing Pipeslink

\n

You can test pipes without the Angular testing utilities.

\n
\n

For the sample app that the testing guides describe, see the sample app.

\n

For the tests features in the testing guides, see tests.

\n
\n

Testing the TitleCasePipelink

\n

A pipe class has one method, transform, that manipulates the input\nvalue into a transformed output value.\nThe transform implementation rarely interacts with the DOM.\nMost pipes have no dependence on Angular other than the @Pipe\nmetadata and an interface.

\n

Consider a TitleCasePipe that capitalizes the first letter of each word.\nHere's an implementation with a regular expression.

\n\nimport { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({name: 'titlecase', pure: true})\n/** Transform to Title Case: uppercase the first letter of the words in a string. */\nexport class TitleCasePipe implements PipeTransform {\n transform(input: string): string {\n return input.length === 0 ? '' :\n input.replace(/\\w\\S*/g, (txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase() ));\n }\n}\n\n\n\n

Anything that uses a regular expression is worth testing thoroughly.\nUse simple Jasmine to explore the expected cases and the edge cases.

\n\ndescribe('TitleCasePipe', () => {\n // This pipe is a pure, stateless function so no need for BeforeEach\n const pipe = new TitleCasePipe();\n\n it('transforms \"abc\" to \"Abc\"', () => {\n expect(pipe.transform('abc')).toBe('Abc');\n });\n\n it('transforms \"abc def\" to \"Abc Def\"', () => {\n expect(pipe.transform('abc def')).toBe('Abc Def');\n });\n\n // ... more tests ...\n});\n\n\n\n

Writing DOM tests to support a pipe testlink

\n

These are tests of the pipe in isolation.\nThey can't tell if the TitleCasePipe is working properly as applied in the application components.

\n

Consider adding component tests such as this one:

\n\nit('should convert hero name to Title Case', () => {\n // get the name's input and display elements from the DOM\n const hostElement = fixture.nativeElement;\n const nameInput: HTMLInputElement = hostElement.querySelector('input');\n const nameDisplay: HTMLElement = hostElement.querySelector('span');\n\n // simulate user entering a new name into the input box\n nameInput.value = 'quick BROWN fOx';\n\n // Dispatch a DOM event so that Angular learns of input value change.\n // In older browsers, such as IE, you might need a CustomEvent instead. See\n // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill\n nameInput.dispatchEvent(new Event('input'));\n\n // Tell Angular to update the display binding through the title pipe\n fixture.detectChanges();\n\n expect(nameDisplay.textContent).toBe('Quick Brown Fox');\n});\n\n\n\n \n
\n\n\n" }