2016-04-08 69 views
2

我有這樣一種服務:基本服務測試

login.service.ts

import { Injectable } from 'angular2/core'; 
import { Http, Response, Headers } from 'angular2/http'; 
import { Config } from '../common/config'; 

@Injectable() 
export class LoginService { 

    constructor(public http: Http) { } 
    response: JSON; 
... 

    getAuthenticate(username, password) { 
     let headers = new Headers(); 
     const REST_BASE_URL = Config.GET_REST_BASE_URL; 
     let query = '?userid=' + username + ' +&action=authenticate&password=' + password; 
     headers.set('Accept', 'application/json'); 
     return this.http.get(REST_BASE_URL + query, { 
     headers: headers 
     }).map((res: Response) => res.json()); 
    } 
} 

我需要編寫例如測試getAutenticate()方法。不知道我應該如何注入這個Http(模擬與真正的休息服務)。這是我的出發點:

import { it, describe, expect, inject, beforeEachProviders} from 'angular2/testing'; 
import {Http} from 'angular2/http'; 
import { LoginService } from './login.service'; 

class MockLoginService extends LoginService { 
    // todo something 
} 

describe('login service',() => { 
    beforeEachProviders(() => [ 
     provide(TestService, {useClass: MockLoginService}), Http 
    ]); 

    // beforeEachProviders(() => [LoginService, Http]); 
    it('should find credentials', inject([LoginService], (myService:MockLoginService) => { 
     console.log('HERE ', myService.getAutenticate('user1', 'pass1')); 
     expect(true).toBe(true); 
    })); 
}); 

什麼是一個好方法?

回答

4

實際上,要測試您的LoginService,您需要嘲笑其依賴關係而不是服務本身。在這種情況下,您需要用MockBackend之一替換XHRBackend類。

beforeEachProviders(() => { 
    return [ 
    HTTP_PROVIDERS, 
    provide(XHRBackend, { useClass: MockBackend }), 
     HttpService 
    ]; 
}); 

然後,你可以注入XHRBackend,並認購其connections財產攔截請求並返回自己的迴應。

這裏是一個服務的樣本稱爲HttpService

it('test HTTP service', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => { 
    mockBackend.connections.subscribe(
     (connection: MockConnection) => { 
      connection.mockRespond(new Response(
       new ResponseOptions({ 
        body: ['some content'] 
       }))); 
    }); 

    httpService.getMethod().subscribe(
     items => { 
      expect(items).toEqual(['test']); 
     }, 
     () => { 
      console.log('error'); 
     }); 
})); 

HttpService可能是以下幾點:

@Injectable() 
export class HttpService { 
    constructor(private http:Http) { 
    } 

    getMethod() { 
    return this.http.get('/test').map(res => res.json()); 
    } 
} 
+0

再次感謝您,亨利,我想你的例子:這個問題是我得到的錯誤:失敗:httpService.getMethod不是一個函數... –

+0

你在'HttpService'類上有'getMethod'方法嗎? –

+1

所以我不知道我做了什麼,但:根據你的回答,我試着https://github.com/krimple/angular2-webpack-demo-routing-and-http。我有同樣的問題。然後我看了一下服務,我注意到有一個導入有'rxjs/add/operator/map';我補充說,服務和工作! –