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

问题描述 投票:0回答:1

认为它仍然是重复的问题。到目前为止,我还没有任何解决方案。

当前,我面临的属性'subscribe'在'Subscription'类型上不存在。您是说“退订”吗?

我已经尝试过几种SO解决方案。但没有锁。

需要帮助指出我所缺少的.. !!

到目前为止,我在下面

my-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);
    });
  }
}

my-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);
    });
  });
});

即使经过很多教程,我也无法理解我在做什么错。

感谢伙伴

angular unit-testing jasmine karma-jasmine
1个回答
0
投票

您在可观察范围内两次致电订阅

this.http.get<dummyModel>(`${this.api.patinetList}`)

有关最佳做法,

更改`

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))
       );
  }
© www.soinside.com 2019 - 2024. All rights reserved.