2017-10-17 109 views
0

我对Angular4相当陌生,需要为我构建的简单服务编写单元测试,但不知道从哪里开始。Angular4 - 如何测试一个服务

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()方法,不知道如何:

服务仅仅如下包装API调用。另外,我在网上看到过有关测试服务的各种文章,我不确定是否需要嘲笑预期的结果,或者是否应该实际调用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; 
} 

任何帮助,非常感谢!

回答

0

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

这样做的一种方法是模拟用于处理真实数据的库/依赖项/代码部分。

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

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

您可以找到更多的细节here

+0

好酷 - 所以最好测试时不依赖于真正的api。所以我嘲笑实际的电话。有没有人用HttpClient作为依赖模拟结果测试服务的好例子? –

+0

你总是可以尝试使用'spyOn'来窥探一种方法。检查此答案的用法:https://stackoverflow.com/questions/30658525/spy-on-a-service-method-call-using-jasmine-spies – eminlala