2

Angular6 - Unit testing error “Cannot read property 'subscribe' of undefined”

I was writing a unit test for an angular component which is having several dependencies. One of those dependent service has some properties as observables. I tried to mock this service but is throwing error as in title,

spec.ts

describe('Component', () => {
let mockService= jasmine.createSpyObj(['property1', 'property2', 'property3']);

beforeEach(async(() => {
    TestBed.configureTestingModule({
declarations: [testComponent],
providers: [
......someOther,
{ provide service, useValue: mockService},
......someOther
]
}).compileComponents();

fixture = TestBed.createComponent(testComponent);
component = fixture.componentInstance;
}));

it('should be created', () => {
expect(component).toBeTruthy();
  });
});

ts file has

this.Service.property1.subscribe(() => {})
this.Service.property2.subscribe(() => {})
this.Service.property3.subscribe(() => {})

Expect test case to pass but fails with error as in title

Arun Mohan
  • 21
  • 2

1 Answers1

0

Instead of creating a spy in this way try to create spy in

then

block of

compileComponents

Like this

let service:Service

.compileComponents().then(()=>{

  spyOn(service:Service, 'any method / property').and.returnValue(Observable.of(MOCKDATA));

)}

I hope it helps

siddharth shah
  • 1,139
  • 1
  • 9
  • 17