2017-10-17 85 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