Angular Unit Test – Pipe, Service

スポンサーリンク

Pipe Unit Test

In Angular pipe – Create pipe, create pipe. Let’s test this pipe.

When we create pipe, we use ng command

ng g pipe grep

To run this, generate

  • grep.pipe.ts
  • grep.pipe.spec.ts

So, spec.ts is generated automatically.

grep.pipe.ts

import { ValueTransformer } from '@angular/compiler/src/util';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'grep'
})
export class GrepPipe implements PipeTransform {

  transform(values: any[], callback: (item: any) => boolean) {
    if (!Array.isArray(values)) {
      return values;
    }
    return values.filter(callback);
  }
}

This pipe checks, find values from target array, based on callback function. callback function is condition to filter

grep.pipe.spec.ts

By default, create an instance test is generated.

import { GrepPipe } from './grep.pipe';

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

  it('Pipe test', () => {
    const pipe = new GrepPipe();
    let list = ['Nezuko', 'Mitsuri' , 'Tama', 'Daki'];
    expect(pipe.transform(list, myFilter)).toEqual(['Nezuko', 'Mitsuri']);
  })

  function myFilter(value : string): boolean {
     return value.length > 5
  }
});

See.

Create pipe using new, and call transform method directly and check results.

Service Unit Test

Next is Service. In this time, only simple service not Http.

Create service with command

ng g service messageservice

Same as pipe, spec.ts is also generated.

messageservice.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MessageserviceService {

  messages: string[] = [];

  constructor() { }

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

This service is just manage message list. using add and clear methods.

messageservice.service.spec.ts

import { TestBed } from '@angular/core/testing';

import { MessageserviceService } from './messageservice.service';

describe('Simple MessageService Test', () => {
  let service: MessageserviceService;
  beforeEach(() => {
    service = new MessageserviceService();
  });

  it('should have no message to start', () => {
    expect(service.messages.length).toBe(0);
 })
 
 it('should add a message add is called', () => {
     service.add('message1');
    expect(service.messages.length).toBe(1);
 })
 
 it('should remove all messages when clear is called', () => {
     service.add('message1');
  service.clear();
    expect(service.messages.length).toBe(0);
 })
});

Delete default test codes. Create service using new. And call method directly. Not difficult.

TypeScript
スポンサーリンク
Professional Programmer2

コメント