首页 > 解决方案 > Angular 测试在单独运行时有效,但在与其他 tets 一起运行时失败

问题描述

我遇到了一个问题,即当它与我的应用程序中的所有其他测试一起运行时,测试始终失败。返回的错误是

未捕获的类型错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。抛出

以下是问题中的两个类和测试文件。

通知类

export class Notification {
  message: string;
  category: string;
  clearAll: boolean = false;

  constructor(message: string, category?: string, clear?: boolean) {
    this.message = message;
    if (category) {
      this.category = category;
    }
    if (clear) {
      this.clearAll = clear;
    }
  }
}

通知服务类

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Notification } from '../shared/notification';;


@Injectable({
  providedIn: 'root'
})
export class NotificationsService {
  notificationSubject: Subject<Notification>;
  notification$: Observable<any>;


  constructor() {
    this.notificationSubject = new Subject<Notification>();
    this.notification$ = this.notificationSubject.asObservable();
  }

  getNotificationObservable(): Observable<Notification> {
    return this.notification$;
  }

  /**
   * Method allowing a notification to be added so that subsribers can deal with is     according.
   * @param {Notification}notification
   */
  addNotifications(notification: Notification): void {
    this.notificationSubject.next(notification);
  }
}

通知服务.spec.ts

import { NotificationsService } from './notifications.service';

describe('NotificationService', () => {
  let service: NotificationsService;

  beforeEach(() => { service = new NotificationsService(); });

  it('to be created', () => {
    expect(1 === 1).toBeTruthy();
  });

});

如果我专注地运行这个测试,它就会通过。IE

fit('to be created', () => {
    expect(1 === 1).toBeTruthy();
  });

从我所做的搜索来看,似乎有以下建议:

我怀疑第二个子弹可能是这种情况,但我似乎无法确定问题所在。

标签: angularkarma-jasmineangular-test

解决方案


我遇到过同样的问题。问题不在于失败的测试,而在于之前的测试。我最终删除了以前的测试,并解决了这个问题。


推荐阅读