如何在Angular中为HTTPClient get() 方法服务编写单元测试用例?

How to write unit test case for HTTPClient get() method service in Angular?

目前,我遇到一个错误:

Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?

需要帮助指出我遗漏的内容。

我的-service.ts

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {dummyModel} from "./patient2020/dummy1.model";
import {map} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})


export class RecentPatList {

  api = {  patinetList: `/list/version2020/may` };
  constructor(private http: HttpClient) {}


 testGetCall() {
    return this.http.get<dummyModel>(`${this.api.patinetList}`).subscribe(resp => {
      console.log("RESPONSE", resp);
    });
  }
}

我的-service.spec.ts

import { RecentPatList } from './recentList.service';
import { TestBed, getTestBed, inject } from '@angular/core/testing';
import {
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';
import { Observable } from 'rxjs/Observable';

describe('RecentPatList', () => {
  let injector;
  let service: RecentPatList;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [RecentPatList]
    });

    injector = getTestBed();
    service = injector.get(RecentPatList);
    httpMock = injector.get(HttpTestingController);
  });

  describe('#testGetCall', () => {
    it('should return an Observable<[]>', () => {
      const dummyUsers = [
        {
          // test data 0        
          {
            // netsted test data 0
          }
        },
        {
          // test data  1        
          {
            // netsted test data 1
          }
        }
      ];

      service.testGetCall().subscribe(data => {
        expect(data.length).toBe(2);
        expect(data).toEqual(dummyUsers);
      });

      const req = httpMock.expectOne(`/list/version2020/may`);
      expect(req.request.method).toBe('GET');
      req.flush(dummyUsers);
    });
  });
});

即使看了很多教程,我也无法理解我做错了什么。

您正在调用 subscribe on subscription 就像错误所说的那样。 testGetCall() returns 一个订阅。

testGetCall 中将 .subscribe() 更改为 pipe()

为了获得最佳实践,

改变 `

testGetCall() {
    return this.http.get<dummyModel>(`${this.api.patinetList}`).subscribe(resp => {
      console.log("RESPONSE", resp);
    });
  }`

 testGetCall() {
    return this.http.get<dummyModel>(`${this.api.patinetList}`)
      .pipe(
        tap((resp)=> console.log("RESPONSE", resp))
       );
  }