Angular单元测试TypeError:this.http.get(...)。pipe不是函数

时间:2018-06-20 12:40:43

标签: angular unit-testing typescript jasmine rxjs

我正在按照此示例进行服务的单元测试(获取来自Spring应用程序后端的请求)https://angular.io/guide/testing#testing-http-services

服务类别:

@Injectable()
export class TarifService {

  constructor(private messageService: MessageService, private http: HttpClient) { }

  public getTarifs(): Observable<Tarif[]> {
    return this.http.get<Tarif[]>(tarifffsURL).pipe(
      tap(() => {}),
      catchError(this.handleError('getTarifs', []))
    );
  }
}

单元测试

describe('TarifService', () => {

  let tarifService: TarifService;
  let httpClientSpy: { get: jasmine.Spy };
  let expectedTarifs;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ToastrModule.forRoot(), HttpClientModule, HttpClientTestingModule],
      providers: [TarifService, HttpClient, MessageService]
    });

    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
    tarifService = new TarifService(<any> MessageService,<any> httpClientSpy);

  });


  it('should be created', inject([TarifService], (service: TarifService) => {
    expect(service).toBeTruthy();
  }));


  it('should return expected tarif (HttpClient called once)', () => {
    const expectedTarifs: Tarif[] =
      [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];

    httpClientSpy.get.and.returnValue(expectedTarifs);

    tarifService.getTarifs().subscribe(
      tarifs => expect(tarifs).toEqual(expectedTarifs, 'expected tarifs'),
      fail
    );
    expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
  });
});

运行测试时,我一直遇到此错误

TarifService should return expected tarif (HttpClient called once)
TypeError: this.http.get(...).pipe is not a function

这可能是什么原因?

2 个答案:

答案 0 :(得分:7)

问题在于,调用spy时,它将返回Array,而Array没有pipe函数。您需要从Observable返回spy,就像这样

const expectedTarifs: Tarif[] =
  [{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];

httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs));

查看returnValueObservable.of(expectedTarifs)的方式。 Observable.of创建一个Observable,它会发出一个您指定为自变量的值,一个接一个地发出,然后发出一个完整的通知。 See the docs

希望有帮助

答案 1 :(得分:1)

为了使我的工作,我必须这样做:

import { from } from 'rxjs';

然后:

return from([expectedTarifs]);