简体   繁体   English

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

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

Currently, I'm facing an error:目前,我面临一个错误:

Property 'subscribe' does not exist on type 'Subscription'. “订阅”类型上不存在属性“订阅”。 Did you mean 'unsubscribe'?您的意思是“取消订阅”吗?

Need help to point out what I'm missing.需要帮助指出我所缺少的。

my-service.ts我的服务.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我的服务.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);
    });
  });
});

I couldn't understand what I'm doing wrong even after gone through lots of tutorials.即使经过大量教程,我也无法理解自己做错了什么。

You are calling subscribe on subscription like the error said.您正在调用订阅订阅,就像错误所说的那样。 testGetCall() returns a subscription. testGetCall()返回一个订阅。

Change .subscribe() to pipe() in testGetCall .testGetCall .subscribe()更改为pipe()

For best practices,对于最佳实践,

change `改变`

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM