Angular4 - 如何测试服务

时间:2017-10-17 10:36:14

标签: angular unit-testing service karma-jasmine observable

我对Angular4很新,需要为我已经建立的简单服务编写单元测试,但不知道从哪里开始。

该服务只是按如下方式包含api调用:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

import { KeyValuePair } from '../../models/keyvaluepair';
import { environment } from './../../../environments/environment';

// Lookups api wrapper class.
@Injectable()
export class LookupsService {

    private servicegApiUrl = '';

    public constructor( private http : HttpClient ) {  
        // Build the service api url, uring the environment lookups api url, plus controller name to reference.
        this.servicegApiUrl = environment.webApiUrl + 'Lookups/';
    }

    // Get the hubs from the web api.
    public getHubs() :  Observable<KeyValuePair<number>[]> {
        // Carry out http get and map the result to the KeyValuePair number object.
        return this.http.get<KeyValuePair<number>[]>(this.servicegApiUrl + 'Hubs').map(res => { return res; });
    }
}

我需要测试我的getHubs()方法并且不知道如何。另外,我在网上看过各种关于测试服务的文章,我不确定我是否要模拟预期的结果,或者这实际上是否应该调用Web服务。我有这段代码,但 期待 似乎永远不会被执行:

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { LookupsService } from './Lookups.Service';
import { KeyValuePair } from './../../models/KeyValuePair';

describe(`LookupsService tests`, () => {

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
        HttpClientTestingModule
      ],
      providers: [
        LookupsService
      ]
    });
  });



  it(`should get results from the web method`, async(inject( [ LookupsService, HttpTestingController ],

    (service: LookupsService, backend: HttpTestingController) => {

      service.getHubs().subscribe((hubs : KeyValuePair<number>[]) => {
        // This code never seems to run...
        console.log(hubs.length);
        expect(hubs.length).toBeGreaterThan(0);
      });
  })));

});

为了完整性,KeyValuePair类如下所示:

export class KeyValuePair<T> {
    Key : string;
    Value : T;
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

单元测试应该(至少在大多数情况下)测试代码而不使用真正的API或数据库调用。

执行此操作的一种方法是模拟用于处理实际数据的库/依赖项/代码部分。

在您的情况下,您可以创建一个FakeHttpClient服务来处理您的虚假数据,并在您测试LookupService服务时使用它。初始化将是这样的:

var lookupService = new LookupService(new FakeHttpClientService());
//rest of your code for testing LookupService class.

您可以找到更多详情here