Cannot read property 'subscribe' of undefined after running npm test (Angular 2 unit testing)
Asked Answered
F

1

51

I've created a testing (spec) file for a component I'm testing. But when I run the test, it gives me an error saying

Cannot read property 'subscribe' of undefined
TypeError: Cannot read property 'subscribe' of undefined
at ComponentUndertest.ngOnInit

which is obvious because I have subscribed to something in my ngOnInit() method, but can I ignore the subscription during the test? Or can I fake a subscription during testing? I have googled a lot about this issue but couldn't find anything related with angular2 testing.

Falsify answered 19/10, 2016 at 22:5 Comment(0)
W
78

Assuming you have a service that has a method that returns an observable, say

class SomeService {
  getData(): Observable<Data> {}
}

You could....

Create a spy1 where you return an object with a noop subscribe function.

let mockSomeService = {
  getData: () => {}
}

TestBed.configureTestingModule({
  providers: [
    { provide: SomeService, useValue: mockSomeService }
  ]
})

it('...', () => {
  spyOn(mockSomeService, 'getData').and.returnValue({ subscribe: () => {} })
  // do stuff
  expect(mockSomService.getData).toHaveBeenCalled();
})

You could...

Return an actual observable in the spy

spyOn(mockSomeService, 'getData').and.returnValue(Observable.of(someData))

Maybe this will be preferred over the noop subscribe method, because if the call on the service is changing something in the component, this is something you probably will want to test

You could...

Do something like in this post.


1 - See more about spies

Wrinkle answered 20/10, 2016 at 1:6 Comment(1)
You can also move returnValue action to mock : let mockSomeService = { getData: () => { return {subscribe: () => {} } } }Weese

© 2022 - 2024 — McMap. All rights reserved.