Sub topic 13
Unit Testing a Custom Pipe
This chapter assumes you can write TypeScript, know how Angular standalone components import pipes, and have already written a custom pipe with @Pipe and PipeTransform. It also assumes you have seen a Jasmine or Jest style describe/it/expect test. The examples use describe, it, expect and beforeEach, which work the same in Jasmine (the Angular CLI default) and Jest.
Why pipes are easy to test
A pipe is a plain TypeScript class with one important method, transform. The @Pipe decorator only adds metadata that the Angular compiler reads. It does not change how you construct the class or call its methods. So you can create an instance with new and call transform directly, with no TestBed, no component fixture and no change detection.
This gives you three benefits:
- Tests run fast, because Angular does not have to compile anything.
- Failures point at the pipe, not at template wiring.
- Test inputs are just function arguments, so edge cases are cheap to write.
The cost is that a class-level test says nothing about whether the pipe is registered in a template correctly. Section "Testing the pipe inside a template" covers that.
The pipe under test
The tests below use the TruncatePipe from the chapter on custom pipes. Here it is again so you can see exactly which behaviors need to be covered.
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;
}
}Reading the code, the behaviors are:
- A
null,undefinedor empty string returns an empty string. - A string longer than
limitis cut tolimitcharacters, trailing whitespace is removed, and the ellipsis is appended. - A string at or under
limitis returned unchanged. limitdefaults to 20 andellipsisdefaults to'…'.
Each of these should have at least one test.
A first test file
Place the spec file next to the pipe, named truncate.pipe.spec.ts. The Angular CLI generates this name when you run ng generate pipe truncate.
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('');
});
});The pipe is created once in the describe block. That is safe here because TruncatePipe keeps no state between calls. If a pipe holds state, such as a cache, create a fresh instance in beforeEach so tests cannot affect each other.
Covering the edge cases
Two tests are not enough. The following spec checks each behavior listed above, including the boundaries where off-by-one mistakes usually hide.
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe', () => {
let pipe: TruncatePipe;
beforeEach(() => {
pipe = new TruncatePipe();
});
describe('empty input', () => {
it('returns an empty string for null', () => {
expect(pipe.transform(null)).toBe('');
});
it('returns an empty string for undefined', () => {
expect(pipe.transform(undefined)).toBe('');
});
it('returns an empty string for an empty string', () => {
expect(pipe.transform('')).toBe('');
});
});
describe('length boundary', () => {
it('leaves text shorter than the limit unchanged', () => {
expect(pipe.transform('abc', 5)).toBe('abc');
});
it('leaves text exactly at the limit unchanged', () => {
expect(pipe.transform('abcde', 5)).toBe('abcde');
});
it('truncates text one character over the limit', () => {
expect(pipe.transform('abcdef', 5)).toBe('abcde…');
});
});
describe('whitespace', () => {
it('removes trailing spaces before the ellipsis', () => {
expect(pipe.transform('hello world', 6)).toBe('hello…');
});
});
describe('parameters', () => {
it('uses a 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', 3, '...')).toBe('abc...');
});
});
});Look at the whitespace test. The input 'hello world' cut at 6 characters gives 'hello ', and trimEnd() turns it into 'hello'. Without the test, someone could remove trimEnd() during a cleanup and nothing would fail.
The boundary tests use three lengths: under, exactly at, and one over the limit. This trio catches the common mistake of writing >= where > is correct.
A table of cases
When many inputs share one assertion, a loop keeps the spec short. Each iteration registers its own it, so failures name the failing input.
import { TruncatePipe } from './truncate.pipe';
describe('TruncatePipe (table)', () => {
const pipe = new TruncatePipe();
const cases: { input: string | null | undefined; limit: number; expected: string }[] = [
{ input: null, limit: 5, expected: '' },
{ input: '', limit: 5, expected: '' },
{ input: 'abcde', limit: 5, expected: 'abcde' },
{ input: 'abcdef', limit: 5, expected: 'abcde…' },
{ input: 'ab cdef', limit: 3, expected: 'ab…' },
];
cases.forEach(({ input, limit, expected }) => {
it(`transform(${JSON.stringify(input)}, ${limit}) returns ${JSON.stringify(expected)}`, () => {
expect(pipe.transform(input, limit)).toBe(expected);
});
});
});Use plain it blocks when the cases tell different stories. Use a table when only the data changes.
Testing pipes that have dependencies
Some pipes inject services, for example a pipe that reads the current language from a translation service. Do not reach for TestBed first. If the pipe uses the inject() function in a field initializer, it needs an injection context, and TestBed.runInInjectionContext provides one:
import { Injectable, Pipe, PipeTransform, inject } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Injectable({ providedIn: 'root' })
export class Prefix {
value = 'Mr. ';
}
@Pipe({ name: 'greet', standalone: true })
export class GreetPipe implements PipeTransform {
private readonly prefix = inject(Prefix);
transform(name: string): string {
return this.prefix.value + name;
}
}
describe('GreetPipe', () => {
it('uses the injected prefix', () => {
const pipe = TestBed.runInInjectionContext(() => new GreetPipe());
expect(pipe.transform('Smith')).toBe('Mr. Smith');
});
it('works with a replaced service', () => {
TestBed.configureTestingModule({
providers: [{ provide: Prefix, useValue: { value: 'Dr. ' } }],
});
const pipe = TestBed.runInInjectionContext(() => new GreetPipe());
expect(pipe.transform('Jones')).toBe('Dr. Jones');
});
});If the pipe takes its dependency through the constructor instead, pass a hand-made object, such as new GreetPipe({ value: 'Dr. ' }). That keeps the test free of TestBed.
Testing the pipe inside a template
A direct transform call proves the logic. It does not prove that the pipe name is spelled correctly, that the component lists the pipe in imports, or that parameters are written in the right order after the colons. One small host-component test covers those wiring risks.
import { Component } from '@angular/core';
import { ComponentFixture, 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: string | null = 'abcdefghij';
}
describe('TruncatePipe in a template', () => {
let fixture: ComponentFixture<HostComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HostComponent],
}).compileComponents();
fixture = TestBed.createComponent(HostComponent);
});
it('renders the truncated text', () => {
fixture.detectChanges();
const p: HTMLElement = fixture.nativeElement.querySelector('p');
expect(p.textContent).toBe('abcde…');
});
it('renders nothing for a null value', () => {
fixture.componentInstance.text = null;
fixture.detectChanges();
const p: HTMLElement = fixture.nativeElement.querySelector('p');
expect(p.textContent).toBe('');
});
});Keep the host component inside the spec file. It exists only for the test. One or two template tests per pipe are enough, because the class tests already cover the logic.
Testing impure pipes
An impure pipe (pure: false) runs on every change detection cycle, and the ActiveOnlyPipe from the chapter on pure and impure pipes is a good example. Its transform method is still a plain function, so a class-level test works the same way:
import { ActiveOnlyPipe } from './active-only.pipe';
describe('ActiveOnlyPipe', () => {
const pipe = new ActiveOnlyPipe();
it('keeps only active items', () => {
const items = [
{ name: 'a', active: true },
{ name: 'b', active: false },
];
expect(pipe.transform(items)).toEqual([{ name: 'a', active: true }]);
});
it('reflects in-place changes when called again', () => {
const items = [{ name: 'a', active: false }];
expect(pipe.transform(items)).toEqual([]);
items[0].active = true;
expect(pipe.transform(items).length).toBe(1);
});
});Notice toEqual rather than toBe. A filtering pipe returns a new array on each call, so toBe would compare references and always fail. The second test mutates the array and calls transform again, which is what an impure pipe is designed to handle.
A class-level test cannot show whether Angular calls the pipe again after a mutation. That depends on the pure flag and on change detection. To check it, use a host component, mutate the array, call fixture.detectChanges(), and read the rendered output. If you switch the flag back to true, this test fails, which is the point.
Choosing what to test
| Question | Test type |
|---|---|
| Does `transform` return the right value for each input? | Class-level, with `new` |
| Does the pipe handle `null` and `undefined`? | Class-level |
| Does the pipe need a service? | `TestBed.runInInjectionContext` or a constructor argument |
| Is the pipe name and import wiring correct? | Host component with `TestBed` |
| Does an impure pipe respond to in-place changes? | Host component and `detectChanges()` |
Common mistakes
- Testing only the happy path. Pipes receive
nullfrom unresolved async values and optional fields. Always test empty input. - Comparing arrays or objects with
toBe. UsetoEqualfor values andtoBeonly for primitives or when you mean reference identity. - Depending on the machine's locale or time zone. A test that formats a date with the default locale can pass locally and fail in CI. Pass the locale to the constructor, as in
new DatePipe('en-US'), and build dates withnew Date(2024, 0, 15), which uses local time on both the input and the output side. - Sharing mutable state between tests. Create the pipe in
beforeEachwhen it holds a cache or counter. - Using
TestBedfor everything. It slows the suite and hides which layer failed.
How the pieces fit
Exercises
Exercise
Why can you test TruncatePipe.transform without TestBed?
Show answer
A pipe is an ordinary class. The @Pipe decorator only adds metadata for the Angular compiler, so new TruncatePipe() works and transform is a normal method call. TestBed is needed only when you want to check template wiring, change detection, or a pipe that uses inject().
Exercise
Write a spec for a pipe RepeatPipe with transform(value: string, times = 2): string that returns value repeated times times. Include one test for the default and one for times of 0.
Show answer
import { RepeatPipe } from './repeat.pipe'; describe('RepeatPipe', () => { const pipe = new RepeatPipe(); it('repeats twice by default', () => { expect(pipe.transform('ab')).toBe('abab'); }); it('returns an empty string when times is 0', () => { expect(pipe.transform('ab', 0)).toBe(''); }); });
Exercise
A test for a pipe that formats a date passes on your laptop and fails in the CI server. Name two likely causes and a fix for each.
Show answer
First, the default locale differs between machines. Fix it by passing a locale explicitly, for example new DatePipe('en-US'). Second, the time zone differs, or the test uses the current time. Fix it by building the input date from fixed local components, such as new Date(2024, 0, 15), and by never asserting on new Date().