Angular unit tests TypeError: this.http.get(…).pipe is not a function

前端 未结 2 1626
梦毁少年i
梦毁少年i 2021-01-17 19:45

I\'m following this example to make a unit test for service (get request coming from spring app backend) https://angular.io/guide/testing#testing-http-services

Servi

相关标签:
2条回答
  • 2021-01-17 20:28

    I had to do this to get mine to work:

    import { from } from 'rxjs';
    

    then:

    return from([expectedTarifs]);
    
    0 讨论(0)
  • 2021-01-17 20:39

    The problem is that when your spy is being called, it is returning an Array, and Array does not have a pipe function. You need to return an Observable from your spy, something like this

    const expectedTarifs: Tarif[] =
      [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
    
    httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs));
    

    See how the returnValue is Observable.of(expectedTarifs). Observable.of creates an Observable that emits some values you specify as arguments, immediately one after the other, and then emits a complete notification. See the docs

    In the latest versions of rxjs we can use the of operator

    import { of } from 'rxjs';
    
    //... omitting some code here for brevity 
    
    const expectedTarifs: Tarif[] =
      [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
    
    httpClientSpy.get.and.returnValue(of(expectedTarifs));
    

    Hope it helps

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