How to Test Pipe in Angular: Simple Guide with Examples
To test a pipe in Angular, create an instance of the pipe class and call its
transform method with test inputs. Use Jasmine or your test framework to assert the expected output from the transform method.Syntax
Testing an Angular pipe involves creating an instance of the pipe class and calling its transform method directly with input values. The transform method is where the pipe logic lives and returns the transformed output.
Example parts:
const pipe = new YourPipe();- creates the pipe instance.pipe.transform(value, args)- calls the pipe logic with inputvalueand optionalargs.- Use assertions to check if the output matches expected results.
typescript
const pipe = new YourPipe(); const result = pipe.transform(inputValue, optionalArgs); expect(result).toBe(expectedOutput);
Example
This example shows how to test a simple Angular pipe that capitalizes the first letter of a string.
typescript
import { CapitalizePipe } from './capitalize.pipe'; describe('CapitalizePipe', () => { let pipe: CapitalizePipe; beforeEach(() => { pipe = new CapitalizePipe(); }); it('transforms "hello" to "Hello"', () => { expect(pipe.transform('hello')).toBe('Hello'); }); it('returns empty string when input is empty', () => { expect(pipe.transform('')).toBe(''); }); it('does not change already capitalized string', () => { expect(pipe.transform('Angular')).toBe('Angular'); }); });
Output
All tests pass successfully.
Common Pitfalls
Common mistakes when testing pipes include:
- Not creating a new pipe instance before each test, causing shared state issues.
- Forgetting to call the
transformmethod and testing the pipe class itself. - Not testing edge cases like empty or null inputs.
- Trying to test pipes inside Angular templates instead of unit testing the pipe class directly.
typescript
/* Wrong way: Testing pipe class without calling transform */ const pipe = new CapitalizePipe(); expect(pipe).toBeDefined(); // This does not test functionality /* Right way: Call transform method */ expect(pipe.transform('test')).toBe('Test');
Quick Reference
Tips for testing Angular pipes:
- Create a fresh pipe instance in
beforeEach. - Call
transformwith different inputs to cover cases. - Use Jasmine or Jest for assertions.
- Test edge cases like empty, null, or unexpected inputs.
- Keep tests focused on pipe logic, not Angular templates.
Key Takeaways
Always test the pipe's transform method directly with various inputs.
Create a new pipe instance before each test to avoid shared state.
Include edge cases like empty or null inputs in your tests.
Avoid testing pipes inside templates; focus on unit tests for pipe classes.
Use Jasmine or Jest assertions to verify expected output.