How to create a pipe in angular and test it using Jasmine

Rohan Thakur
3 min readNov 7, 2021

Pipe in angular is a useful tool to transform a string or date or similar data for display. In this article, we will create a pipe to reverse a string and will test it using jasmine, which is a tool for unit testing inbuild in angular projects.

Create an Angular Project

We will start by creating a new angular project through angular CLI

ng new learnPipes

The above command will create an angular project for us.

Create a Pipe

We will again use angular CLI for creating a pipe.

ng g p reverse

In the above command, g and p are shorthand for ‘generate’ and ‘pipe’.

Transform output

Your ‘reverse.pipe.ts’ will look like this

import { Pipe, PipeTransform } from ‘@angular/core’;

@Pipe({

name: ‘reverse’

})

export class ReversePipe implements PipeTransform {

transform(value: unknown, …args: unknown[]): unknown {

return null;

}

}

the pipe decorator contains the name of the pipe. Inside ReversePipe class the transform function is responsible for changing the value of the data that we will pass to our pipe. Its arguments contain value (which will be the original copy of the data that the pipe will receive) and args (additional arguments send along). You can add arguments in a pipe like this

{{ string-data | pipe-name:argv }}

string-data denotes the data that needs to be transformed, pipe-name denotes the name of pipe and argv denotes additional arguments that we want to send. In this article, we do not need to pass additional arguments. We will transform our string by splitting it into an array and then reversing it using reverse() and putting it back as a string.

Use Pipe

Now in the app-component.html file, we can use the pipe like this

Its output will be,

Test your pipe

When creating a pipe we also get a spec file that is used for testing it using jasmine.

We create an instance of ReversePipe, passed a string ‘hello’ to its transform function, and expected it to equal ‘olleh’. You can run the test using ‘ng test’ command. The output for this test would be,

Thank you,

--

--