在 Jasmine 中模拟 SpyObject 的 Observable
Mocking Observable of SpyObject in Jasmine
我的组件订阅了类似这样的服务的可观察对象:
ngOnInit(): void {
this.sub.add(
this.notesService.notes$.subscribe(notes => {
this.notes = notes.map(note => {
let profilePicture = generateProfilePicture(note.creator)
return {
...note,
color: profilePicture.color,
initials: profilePicture.initials
}
})
})
);
}
在我的单元测试中,我为 NoteService 创建了一个间谍对象。如何存根 note$ observable?
providers: [
ConfirmationService,
{
provide: HttpClient,
useValue: jasmine.createSpyObj("HttpClient", ["get", "post", "put", "delete"])
},
{
provide: NotesService,
useValue: jasmine.createSpyObj("NotesService",
["addNote", "getNotesByRefId", "editNote", "deleteNote"])
}
]
分开输入(需要时使用 as any
):
const trigger = new Subject<any>();
let trigger$: Observable<any>;
beforeEach(() => {
trigger$ = trigger.asObservable().pipe(first());
component.notesService.notes$ = trigger$;
})
it('Should XXX', () => {
trigger$.subscribe(() => {
expect(...);
});
component.ngOnOnInit();
trigger.next('Value that the observable should emit');
})
我的组件订阅了类似这样的服务的可观察对象:
ngOnInit(): void {
this.sub.add(
this.notesService.notes$.subscribe(notes => {
this.notes = notes.map(note => {
let profilePicture = generateProfilePicture(note.creator)
return {
...note,
color: profilePicture.color,
initials: profilePicture.initials
}
})
})
);
}
在我的单元测试中,我为 NoteService 创建了一个间谍对象。如何存根 note$ observable?
providers: [
ConfirmationService,
{
provide: HttpClient,
useValue: jasmine.createSpyObj("HttpClient", ["get", "post", "put", "delete"])
},
{
provide: NotesService,
useValue: jasmine.createSpyObj("NotesService",
["addNote", "getNotesByRefId", "editNote", "deleteNote"])
}
]
分开输入(需要时使用 as any
):
const trigger = new Subject<any>();
let trigger$: Observable<any>;
beforeEach(() => {
trigger$ = trigger.asObservable().pipe(first());
component.notesService.notes$ = trigger$;
})
it('Should XXX', () => {
trigger$.subscribe(() => {
expect(...);
});
component.ngOnOnInit();
trigger.next('Value that the observable should emit');
})