angular - 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();
});
从我所做的搜索来看,似乎有以下建议:
- 以前的测试没有正确地重置测试台,这就是为什么测试在孤立的情况下成功但在与其他人一起运行时失败的原因
- 或者通知类在测试之间共享一个属性,这就是导致问题的原因。
我怀疑第二个子弹可能是这种情况,但我似乎无法确定问题所在。
解决方案
我遇到过同样的问题。问题不在于失败的测试,而在于之前的测试。我最终删除了以前的测试,并解决了这个问题。