Ramesh vemula
Ramesh vemula

Reputation: 17

How to write unit testing for alert service

I am new to writing unit test cases. I'm trying to write test cases for my alert service. I am using angular 7. My alert service and my alert model code like below.

My alert.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { Alert, AlertType } from '../models/alert.model';

@Injectable({
  providedIn: 'root'
})
export class AlertService {
  private subject = new Subject<Alert>();

  constructor() {}

  onAlert(): Observable<Alert> {
    return this.subject
      .asObservable();
  }

  success(message: string) {
    this.alert(new Alert(message, AlertType.Success));
  }

  error(message: string) {
    this.alert(new Alert(message, AlertType.Error));
  }

  info(message: string) {
    this.alert(new Alert(message, AlertType.Info));
  }

  warn(message: string) {
    this.alert(new Alert(message, AlertType.Warning));
  }

  alert(alert: Alert) {
    this.subject.next(alert);
  }

  clear() {
    this.subject.next(null);
  }
}

My alert.model.ts

export class Alert {
  constructor(public message: string, public type: AlertType) {}
}

export enum AlertType {
  Success,
  Error,
  Info,
  Warning
}

Upvotes: 0

Views: 1610

Answers (1)

Manuel Panizzo
Manuel Panizzo

Reputation: 896

in your spec file.

add

export class FakeSubject {
  next(value: any) {}
  asObservable() {}
}

configure your testbed:

TestBed.configureTestingModule({
  providers: [{ provide: Subject, useClass: FakeSubject }],
}),

add a service getter before each test.

  beforeEach(() => {
    service = TestBed.get(AlertService);
  });

add test, you can use this example for another test.

  it('success alert ', () => {
    const spy = spyOn(service, 'alert');
    const message = 'hi!';
    service.success(message);
    expect(spy).toHaveBeenCalledWith(new Alert(message, AlertType.Success));
  });

and your utility methods:

  it('alert ', () => {
    subject = service['subject'];
    const spy = spyOn(subject, 'next');
    const alert = new Alert('hi', AlertType.Success);
    service.alert(alert);
    expect(spy).toHaveBeenCalledWith(alert);
  });

  it('clear ', () => {
    subject = service['subject'];
    const spy = spyOn(subject, 'next');

    service.clear();
    expect(spy).toHaveBeenCalledWith(null);
  });

Upvotes: 3

Related Questions