Testing a Directive and Pipe in Angular

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

An angular application is made up of numerous components, services, directives, pipelines, and so on. Unit tests for each component are required to build and manage a large programme.

Directives and pipes are also key components of the application that must be tested.

Scope

We will explore testing a directive and pipe in our Angular application in this article using examples.

Introduction

A directive with an attribute specifies how an element, component, or another directive should behave. The directive is used as an attribute on a host element, as indicated by its name.

Testing Attribute Directives

Attributes When modifying an element's style, directives are frequently used, either directly with inline styles or indirectly through classes.

To test an attribute directive, you must first obtain an instance of it, do some kind of action, and then verify that the DOM displays the anticipated changes. Prior to starting the exam writing process.

Example of Testing Directives

Execute the following command to create a new attribute directive using the Angular CLI.

ng generate directive stared

Code:

import { Directive, HostBinding, Input } from '@angular/core';

@Directive({
  selector: '[stared]'
})
export class StaredDirective {

  @Input() stared = true;

  constructor() { }

  @Input("class")
  @HostBinding('class')
  get elementClass(): string {
    if (this.stared) {
      return 'bi-star-fill';
    } else {
      return 'bi-star';
    }
  }
}

How does it Work?

We'll add a CSS class to our HTML element that will specify whether it's a full or empty star based on the input value.

Here is how our component uses it:

<i [stared]="true"></i>

How do We Test a Directive?

Therefore, the first step in testing our new directive is to design a fake test component that makes use of it.

import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { StaredDirective } from './stared.directive';

@Component({
  template: `<i [stared]="true"></i>`
})
class TestComponent { }

describe('StaredDirective', () => {

  let fixture: ComponentFixture<TestComponent>;

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [TestComponent, StaredDirective]
    })
    .createComponent(TestComponent);

    fixture.detectChanges();
  })
});

After that, a test case will be written to ensure that the right class has been added.

it('should be stared', () => {
    var element: HTMLElement = fixture.nativeElement.querySelector("i"); // query the proper element inside our test component's template.
    expect(element.className).toEqual("bi-star-fill");
});

Testing Pipes

Pipes transform the input before returning the modified value. Because pipes operate so simply, writing tests for them is easy. The quality of a pipe depends on its input. Any function whose output depends only on the input it receives is said to be pure.

When a function is capable of more than merely returning a value, it is said to have a side effect. Examples of side effects include changing a global variable or making an HTTP call. Because pipes are straightforward functions with no adverse effects, they are easy to evaluate.

Example of Testing Pipes

We'll start by creating a new pipe with the Angular CLI.

ng generate pipe hello
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'hello'
})
export class HelloPipe implements PipeTransform {
  transform(value: unknown, ...args: unknown[]): unknown {
    return `Hello ${value}`;
  }
}

Unit Testing Our New Angular Pipe

import { HelloPipe } from './hello.pipe';

describe('HelloPipe', () => {
  it('create an instance', () => {
    const pipe = new HelloPipe();
    expect(pipe).toBeTruthy();
  });

  it ("expect John to equal Hello Foo", () => {
    const pipe = new HelloPipe();
    expect(pipe.transform("Foo")).toEqual("Hello Foo");
  })
});

We start by generating a new instance of our Angular pipe, same as we did before.

Then, we applied it to a transformed input and evaluated the result.

Conclusion

  • Testing an element's initial state, carrying out the required action, and then testing to ensure that the anticipated change occurred are comparable to testing an attribute or structural directive.

  • Testing pipes is simple because they merely accept a value as input, transform that value, and then return changed input. They have no side effects because they are pure functions, which means they are.

  • When testing pipes, you primarily examine the transform method, which is a component of every pipe. It is the transform method that accepts the many parameters you wish to change and perform.

Free Courses by top Scaler instructors