如何编写警报组件的单元测试

时间:2019-09-18 06:06:26

标签: angular unit-testing

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

我的alert.component.ts

import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { Alert, AlertType } from './models/alert.model';
import { AlertService } from './service/alert.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.css']
})
export class AlertComponent implements OnInit, OnDestroy {
  alerts: Alert[] = [];
  subscription: Subscription;

  constructor(private alertService: AlertService) {}

  ngOnInit() {
    this.subscription = this.alertService.onAlert().subscribe(alert => {
      if (!alert.message) {
        this.alerts = [];
        return;
      }

      this.alerts.push(alert);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  removeAlert(alert: Alert) {
    this.alerts = this.alerts.filter(x => x !== alert);
  }

  cssClass(alert: Alert) {
    if (!alert) {
      return;
    }

    // return css class based on alert type
    switch (alert.type) {
      case AlertType.Success:
        return 'alert alert-success';
      case AlertType.Error:
        return 'alert alert-danger';
      case AlertType.Info:
        return 'alert alert-info';
      case AlertType.Warning:
        return 'alert alert-warning';
    }
  }
}

我的alert.model.ts

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

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

0 个答案:

没有答案