如何编写警报服务的单元测试

时间:2019-09-17 12:01:04

标签: angular unit-testing

我是编写单元测试用例的新手。我正在尝试为我的警报服务编写测试用例。我正在使用angular7。我的警报服务和警报模型代码如下。

我的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);
  }
}

我的alert.model.ts

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

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

1 个答案:

答案 0 :(得分:1)

在您的规格文件中。

添加

insert

配置测试平台:

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

在每次测试之前添加服务获取器。

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

添加测试,您可以将此示例用于其他测试。

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

和您的实用方法:

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