从Angular测试REST服务器而不进行模拟

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Angular测试REST服务器而不进行模拟相关的知识,希望对你有一定的参考价值。

我知道我应该使用模拟测试来自Angular的REST服务器,并且网上有很多例子如何做到这一点。但是假设我想测试一个我完全可以控制的真实服务。

这是工作模拟版本:

describe('SgformsService', () => 
  let sgformsService: SgformsService
  let httpMock: HttpTestingController

  beforeEach(() => 
      TestBed.configureTestingModule(
        providers: [SgformsService],
        imports: [HttpClientTestingModule]
      )
      httpMock = TestBed.get(HttpTestingController);
      sgformsService = TestBed.get(SgformsService);
    );

    it('should return a single item when mocked', () => 
    sgformsService.getSingle().subscribe(
      (sg: SgFormsBase) => 
        expect(sg.id).toEqual(34)
        expect(sg.pat_no).toEqual(1704)
      )
      const req = httpMock.expectOne(
        'http://localhost:8000/getsingle/Endoskopie/1631/2019-03-19/arzt/0', 'call to api');
      expect(req.request.method).toBe('GET');
      req.flush(
        id: 34,
        pat_no: 1704
      )
   );
);

如何将其重定向以使用REST服务器而不是模拟?下面的代码不起作用,因为我不知道如何为SgformsService创建HttpClient。

describe('SgformsService without Mocking', () => 
  let sgformsService: SgformsService
  //let httpClient: HttpClient

  beforeEach(function() 
  //  httpClient = new HttpClient()
  //  sgformsService = new SgformsService(httpClient);
  );

  // https://angular.io/guide/testing#service-tests
  it('should return a single item from server',
    (done: DoneFn) => 
      sgformsService.getSingle().subscribe(
      (sg: SgFormsBase) => 
        expect(sg.id).toEqual(34)
        expect(sg.pat_no).toEqual(1704)
        done()
      );
    );

);
答案

供其他人参考,并在@peinarydevelopment和@Igor的帮助下:

import  TestBed  from '@angular/core/testing';
import  HttpClientModule  from '@angular/common/http';

import  SgformsService  from './sgforms.service';
import  SgFormsBase  from './sgforms-base';

describe('SgformsService', () => 
  let sgformsService: SgformsService

  beforeEach(() => 
      TestBed.configureTestingModule(
        providers: [SgformsService],
        imports: [HttpClientModule]
      )
      sgformsService = TestBed.get(SgformsService);
  );
  it('should return a single item', done =>  
      sgformsService.getSingle().subscribe(
        (sg: SgFormsBase) => 
          expect(sg[0].id).toEqual(7)
          expect(sg[0].pat_no).toEqual(1631)
          done()
        );
      )
)

如果你想使用done,则需要expect结构。如果您只想快速而肮脏地记录结果,则不需要done

另见https://angular.io/guide/testing#service-tests

以上是关于从Angular测试REST服务器而不进行模拟的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Angular 组件中模拟服务功能以进行单元测试

用于模拟响应的 Python Quick Rest API

在单元测试用例中模拟 Angular $window

如何从服务器端模拟复杂的 REST 调用?

如何使用 Spring 在单元测试中模拟远程 REST API?

用于集成测试的 Java 测试项目