In Angular, pipes allow us to transform data before displaying it. Angular comes with a range of built-in pipes, but sometimes we need to write our own custom pipes. Well, in this case, we also have to write unit tests for them.

A pipe is one of the most simple Angular concepts. It's a class annotated with the @Pipe decorator that implements the PipeTransform interface. Concretely, a pipe class has one method, the transform method:

The PipeTransform interface

Because pipes rarely interact with DOM elements, they are very easy to test. Technically, we can test them without using the Angular testing utilities, or TestBed. But it is better to also write some Angular tests for pipes because we will want to detect potential runtime bugs when pipes are used in conjunction with Angular components.

Therefore, we should write two types of unit tests:

  • isolated tests (without TestBed),
  • integrated tests (with TestBed).

In this article, we will learn how to write isolated unit tests for our pipes.
In a next blog post, we will see how to test pipes using TestBed aka Angular tests.

We talk about isolated unit testing when we are testing the pipe as a standalone TypeScript class.

The code for the pipe (mean.pipe.ts)

To begin, let's write a pipe that transforms an array to its mean.

The Mean Pipe

  1. Implement the PipeTransform interface.
  2. Return the mean of the array of numbers.

The full source code of this pipe can be found here.

Testing the pipe in isolation (mean.pipe.spec.ts)

The Mean Pipe - First test

  1. Declare a variable that will hold an instance of the pipe.
  2. Create a new instance of the MeanPipe before every single test runs.
  3. Check that the pipe is correctly instantiated.

Note that we don't need a BeforeEach block because this pipe's transform method is a pure and stateless function.

Once we know that our pipe can be instantiated properly, we can start to write test suites.

The Mean Pipe Specs

  1. The 'Bad Inputs' test suite checks the behavior of our pipe when unexpected values are passed to its transform method.
  2. The 'Calculations' test suite checks if the pipe transforms the data correctly when correct inputs are passed to it.

The full source code of these test suites can be found here


In this article, we learned that there were two ways to unit test Angular pipes: isolated tests and integrated tests. But we put the focus on isolated tests and saw how easy it is to write isolated tests for our pipes.
In my next blog post, we will learn how to write integrated tests for our Angular pipes.
Thank you very much for reading!

If you enjoyed this article, follow @ahasall on Twitter for more content like this.