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

前端 未结 1 650
时光说笑
时光说笑 2021-02-01 01:48

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 und         


        
相关标签:
1条回答
  • 2021-02-01 02:34

    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

    0 讨论(0)
提交回复
热议问题