'Mocking Observable of SpyObject in Jasmine
My component subscribes to an observable of a service like that:
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
}
})
})
);
}
In my unit test I created a spyobject for the NoteService. How can I stub the note$ observable?
providers: [
ConfirmationService,
{
provide: HttpClient,
useValue: jasmine.createSpyObj("HttpClient", ["get", "post", "put", "delete"])
},
{
provide: NotesService,
useValue: jasmine.createSpyObj("NotesService",
["addNote", "getNotesByRefId", "editNote", "deleteNote"])
}
]
Solution 1:[1]
Typings apart (use as any when needed) :
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');
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | temp_user |
