Sub topic 13
Unit Testing a Custom Pipe
This chapter assumes you know TypeScript, Angular standalone components, and how to write a custom pipe with @Pipe and PipeTransform. It also assumes you have a test runner set up. A new Angular project comes with Jasmine and Karma, and the example below works the same way with Jest.
Why pipes are easy to test
A pipe is a plain class with a transform method. A pure pipe takes input and returns output, with no template, DOM, or change detection involved. You can create an instance with new and call transform directly. You don't need the TestBed, which is Angular's test module builder and the slowest part of most component tests.
This gives you fast tests that check one thing: given these arguments, what does transform return?
The pipe under test
This chapter tests the TruncatePipe from the custom pipes chapter.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'truncate', standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string | null | undefined, limit = 20, ellipsis = '…'): string {
if (!value) {
return '';
}
return value.length > limit ? value.slice(0, limit).trimEnd() + ellipsis : value;
}
}The pipe has three behaviors worth checking: it returns an empty string for empty input, it leaves short text alone, and it shortens long text and adds the ellipsis.
A first test
Create one pipe instance at the top of the describe block. Each it block then checks one behavior.
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe', () => {
const pipe = new TruncatePipe();
it('shortens text longer than the limit', () => {
expect(pipe.transform('abcdefghij', 5)).toBe('abcde…');
});
it('returns an empty string for null', () => {
expect(pipe.transform(null)).toBe('');
});
});Sharing one instance is safe here because a pure pipe keeps no state between calls. If your pipe stores data in fields, create a new instance in beforeEach instead, so tests can't affect each other.
Cover the edges
Most pipe bugs appear at boundaries. Write tests for these cases:
- Missing values. Templates often pass
nullorundefined, for example before data arrives. Check both. - Exact limits. A string whose length equals the limit should come back unchanged. A string one character longer should be cut.
- Default parameters. Call
transformwith only the value to confirm that the defaults (20and…) apply. - Custom parameters. Pass a different ellipsis, such as
'...', and check the result. - Whitespace. The pipe calls
trimEnd, so a cut that lands after a space should not leave a trailing space before the ellipsis.
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe edge cases', () => {
const pipe = new TruncatePipe();
it('returns undefined input as an empty string', () => {
expect(pipe.transform(undefined)).toBe('');
});
it('leaves text equal to the limit unchanged', () => {
expect(pipe.transform('abcde', 5)).toBe('abcde');
});
it('cuts text one character over the limit', () => {
expect(pipe.transform('abcdef', 5)).toBe('abcde…');
});
it('uses the default limit of 20', () => {
const text = 'a'.repeat(25);
expect(pipe.transform(text)).toBe('a'.repeat(20) + '…');
});
it('accepts a custom ellipsis', () => {
expect(pipe.transform('abcdefghij', 5, '...')).toBe('abcde...');
});
it('removes trailing spaces before the ellipsis', () => {
expect(pipe.transform('hello world', 6)).toBe('hello…');
});
});The last test is worth reading closely. 'hello world'.slice(0, 6) gives 'hello ', and trimEnd removes the space, so the result is 'hello…'.
When to use the TestBed
Testing transform alone proves the logic is right. It doesn't prove that the template wiring works. Typical wiring mistakes are a wrong name in @Pipe, or forgetting to list the pipe in a component's imports array. For these, add one small test that renders a host component.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { TruncatePipe } from './truncate.pipe';
@Component({
selector: 'app-host',
standalone: true,
imports: [TruncatePipe],
template: `<p>{{ text | truncate:5 }}</p>`,
})
class HostComponent {
text = 'abcdefghij';
}
describe('TruncatePipe in a template', () => {
it('renders the truncated text', () => {
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p').textContent).toBe('abcde…');
});
});Use this kind of test sparingly. Keep the detailed cases in the fast class-level tests and use one template test as a smoke check.
Common mistakes
- Testing only the typical input and missing
nullorundefined. - Using a shared instance for a stateful impure pipe, which lets one test leak into the next.
- Expecting
toBeto compare arrays or objects by content. For results like these, usetoEqual. An impure pipe that filters an array returns a new array each time, sotoBefails even when the contents match.
Exercise
Write two tests for ActiveOnlyPipe, the impure pipe from the pure versus impure chapter, which returns only items whose active property is true. One test checks that inactive items are removed. The other checks that an empty array gives an empty array. Which matcher should you use to compare the results, and why?
Show answer
Create the pipe with new ActiveOnlyPipe(). First test: expect(pipe.transform([{ name: 'a', active: true }, { name: 'b', active: false }])).toEqual([{ name: 'a', active: true }]). Second test: expect(pipe.transform([])).toEqual([]). Use toEqual because filter returns a new array, and toBe compares by reference, so it would fail even when the contents match.