DEV Community

Amadou Sall
Amadou Sall

Posted on • Originally published at amadousall.com on

Angular Pipes: Isolated Unit Testing

Angular Pipes: Isolated Unit Testing

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:

Angular Pipes: Isolated Unit Testing

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 best to 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.

Angular Pipes: Isolated Unit Testing

  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)

Angular Pipes: Isolated Unit Testing

  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.

Angular Pipes: Isolated Unit Testing

  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

Summary

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!

Top comments (0)