unit testing spyOn observable service in angular2

前端 未结 2 1232
后悔当初
后悔当初 2021-01-07 21:41

I have a service (ChildService) which depends on another service (InteractWithServerService). The latter service (InteractWithServerService) is used to make server calls and

相关标签:
2条回答
  • 2021-01-07 22:00

    Using jasmin 2.6.2: get is a function so you need to add the arrow function notation to the answer above:

    providers: [
      { 
        provide: InteractWithServerService,
        useValue: { get: () => Observable.of(..) }
      }
    ]
    
    0 讨论(0)
  • 2021-01-07 22:25

    However, the test case doesn't work and throws "Error: No provider for Http!".

    Because you still have the service in the providers, so Angular is trying to create it still

    providers: [
     InteractWithServerService,
        ChildService],
    

    What you can do instead of creating a mock class is to just do something like

    providers: [
      { 
        provide: InteractWithServerService,
        useValue: { get: Observable.of(..) }
      }
    ]
    

    Here's you're using useValue which provide any object. That will be the value used when injected. In the case above, it is just some arbitrary object with your mock method.

    If you want to spy so that you can provide different values, you could inject the InteractWithServerService, and then do

    spyOn(service, 'get').and.returnValue(Observable.of(...))
    // do test
    

    Another thing you could do is mock the Http with a dummy object

    { provide: Http, useValue: {} }
    

    Now the InteractWithServerService will work (just adding the class to the providers` like you currently have). And you can just spy on it

    let service = TestBed.get(InteractWithServerService);
    spyOn(service, 'get').and.returnValue(..)
    // do test
    
    0 讨论(0)
提交回复
热议问题