【发布时间】:2018-03-06 16:47:01
【问题描述】:
我正在尝试测试一个组件说 notificationComponent,它有一个属性说 notes[],它监听一个服务说 notificationService它有一个可观察的noteAdded,它广播所有发送到服务的通知。
我计划测试 notificationComponent 的方式是:每次向 notificationService 推送通知时,notificationComponent 应该填充 @ 987654323@通过一个函数监听notificationService.noteAdded。
这是组件:
import...;
@Component({
selector: 'app-notifications',
templateUrl: './notifications.component.html',
styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent {
notes: BentoAlertItemOptions[];
constructor(private _notifications: NotificationsService) {
this.notes = [];
_notifications.noteAdded.subscribe(note => {
this.notes.push(note);
});
}
closeAlert($event:any) {
console.info('Alert #', $event, ' is being closed');
}
}
通知服务: 导入..
@Injectable()
export class NotificationsService {
private _notifications = new ReplaySubject<any>(5);
public noteAdded = this._notifications.asObservable();
constructor() {
console.log("notification service constructor");
}
public add(notification: BentoAlertItemOptions) {
console.log("added: ", notification);
this._notifications.next(notification);
}
}
这是我的规范文件:
describe('NotificationsComponent', () => {
let component: NotificationsComponent;
let fixture: ComponentFixture<NotificationsComponent>;
let testBedService:NotificationsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
NotificationsComponent,
MockComponent({
selector: 'bento-alert',
inputs: ['items'],
outputs :['close']
}),
],
providers: [ NotificationsService ]
})
.compileComponents();
testBedService = TestBed.get(NotificationsService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(NotificationsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
//THE TEST THAT FAILS
fit('should push to notes[] for notes added event on the subscribed-service', () => {
let addedNote:any;
addedNote = {
type :'success',
msg : 'Moduled saved!',
timeout : 2500,
closeable: true
}
testBedService.add(addedNote);
expect(true);
});
});
虽然当我对此进行测试时,我收到一条错误消息,提示 cannot read property 'subscribe' of undefined 暗示 notificationComponent.notificationService.noteAdded 未定义。
不知道为什么会这样,我也在测试中使用真正的服务,因为不明白为什么我应该模拟一个简单的服务,比如notificationService
【问题讨论】:
-
我复制并粘贴了您的代码,添加了缺少的导入和分号,并成功运行了您的测试。所以错误必须在导入中。
-
我想通了,它不喜欢我嘲笑第三方的便当组件,所以我不得不将整个真正的便当模块导入到测试台中,谢谢您的评论
标签: angular observable karma-jasmine