Javier G.
Javier G.

Reputation: 43

Testing subscriptions for Angular 8 ngOnInit

I am trying to learn angular unit testing with Karma and Jasmine.

My problem is that when I try to test the component is created, I get: 'TypeError: Cannot read property 'subscribe' of undefined' Because I have subscriptions in the ngOnInit() and I dont know how to test subscriptions inside a method.

Thanks for your help :)

Upvotes: 1

Views: 637

Answers (1)

Yvan
Yvan

Reputation: 1121

All you observable subscribed on the lifecycle on init are the input of your component, so you have to set this value in your test.

it('should create', () => {
    // Here you have to set every input used on your ngOnInit()
    component.cast = new Observable((observer) => { observer.next(true); });
    component.cast2 = new Observable((observer) => { observer.next(true); });
    component.cast3 = new Observable((observer) => { observer.next('test'); });
    expect(component).toBeTruthy();
});

Upvotes: 2

Related Questions