Reputation: 3926
I am using Observable for event subscription but I am unable to test it
Here is my code
Service
export class EventService<T> {
private eventSubject = new Subject<string>();
eventSubject$ = this.eventSubject.asObservable();
dispathEvent(name) {
this.eventSubject.next(name);
}
}
Component
export class UserComponent implements OnInit{
getSub: Subscription;
constructor(private service EventService, private otherService OtherServece)(){}
ngOnInt(){
this.getSub = this.service.eventSubject$.subscribe(name =>{
this.otherService.performAction();
this.otherService.setVar = name;
})
}
}
Spec File
let mockEventService :any;
mockEventService = {
eventSubject: jasmine.createSpyObj('eventSubject', ['next']),
eventSubject$: jasmine.createSpyObj('eventSubject$', ['subscribe']),
};
//some code
providers: [{ provide: EventService, useValue: mockEventService }]
// some code
fixture = TestBed.createComponent(UserComponent);
component = new TeamOvertimeComponent(mockEventService ,mockOtherService);
....
it('should test ngOnInt Service var status', () => {
expect(mockEventService.eventSubject$['subscribe']).toHaveBeenCalled()
fixture.detectChanges();
//
component.ngOnInit();
});
I am seeing issue as
TypeError: this.service.eventSubject$.subscribe is not a function
I tried keeping them in before each but still issue exists
Upvotes: 1
Views: 898
Reputation: 71961
You need to create a spy from the object that has the subscribe
method, in this case the observable:
mockEventService = {
eventSubject: jasmine.createSpyObj('eventSubject', ['next']),
eventSubject$: jasmine.createSpyObj('eventSubject$', ['subscribe']),
};
The rest of the code you can keep the same, as far as I can see. And you can spy on it like this:
expect(mockOvertimeService.eventSubject$['subscribe']).toHaveBeenCalled()
To test the subscribe block you can do something like this (untested code):
mockEventService = {
eventSubject$: { subscribe: jasmine.createSpy().and.callFake((cb) => cb('test')) }
};
otherService = {
performAction: jasmine.createSpy()
};
fixture.detectChanges();
expect(mockEventService.eventSubject$['subscribe']).toHaveBeenCalled();
expect(otherService.performAction).toHaveBeenCalled();
expect(otherService.setVar).toBe('test');
Upvotes: 2