1
votes

I'm getting error TypeError: Cannot read property 'subscribe' of undefined on unit test, how to fix it?

part of my code:

Spec

 it('makes expected calls', () => {
        const item1: item3 = fixture.debugElement.injector.get(item3);
        spyOn(comp, 'item5');
        spyOn(item1, 'item2');
        comp.item4();
        expect(comp.item5).toHaveBeenCalled();
        expect(item1.item2).toHaveBeenCalled();
    });

if I remove this part of spec I get success.

am I using the subscribe() correct way?

2
Could you show the IJ in the constructor?Vega

2 Answers

5
votes

Try providing a mock Observable Jasmine spy returnValue for the spy created for method isPeriodCycleOpen to provide something for the component to be able subscribe to:

import { Observable } from 'rxjs/Observable';

it('makes expected calls', () => {
    const mockResponse = { cyclePeriodOpen: true, deadLineCycle: 'foobar' };

    const cycleServiceStub: CycleService = fixture.debugElement.injector.get(CycleService);
    spyOn(comp, 'setChartData');
    spyOn(cycleServiceStub, 'isPeriodCycleOpen').and.returnValue(Observable.of(mockResponse));
    comp.getCycleStatus();
    expect(comp.setChartData).toHaveBeenCalled();
    expect(cycleServiceStub.isPeriodCycleOpen).toHaveBeenCalled();
});

Hopefully that helps!

0
votes

I think you are missing the return value of the spyon method, try this:

it('makes expected calls', () => {
    const cycleServiceStub: CycleService = 
    fixture.debugElement.injector.get(CycleService);
    spyOn(comp, 'setChartData');
    spyOn(cycleServiceStub, 'isPeriodCycleOpen')
        .and.callFake(() => Observable.of('yourValue')});
    comp.getCycleStatus();
    expect(comp.setChartData).toHaveBeenCalled();
            expect(cycleServiceStub.isPeriodCycleOpen).toHaveBeenCalled();
});