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

僤鯓⒐⒋嵵緔 提交于 2019-12-02 22:04:11
Paul Samsotha

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

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

You could....

Create 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. This is personally they was I usually go. It's just a matter of preference.


1 - See more about spies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!