2016-06-28 92 views
3
import {Injectable} from '@angular/core'; 
import {Http} from '@angular/http'; 

@Injectable() 
export class HttpService { 
    result: any; 

    constructor(private http:Http) { 
    } 

    public postRequest(){ 
     return this.http.get('http://httpbin.org/get');  
    } 
} 

以上是我的代碼,這是我的測試:如何測試Angular2 /打字稿的HTTPService沒有模擬

不想嘲笑什麼,只是測試真正的HTTP連接。

編輯 - 新service.spec文件:

import {beforeEachProviders, beforeEach, it, describe, expect, inject} from '@angular/core/testing'; 
import {HttpService} from '../../providers/http-service/http-service'; 
import {TranslateService} from 'ng2-translate/ng2-translate'; 
import {Goal} from '../../providers/goal/goal'; 
import {NavController} from 'ionic-angular'; 
import {HTTP_PROVIDERS, Http} from '@angular/http'; 

describe('Http Service Test',() => { 

     beforeEachProviders(() => { 
     return [ 
      HTTP_PROVIDERS, 
      HttpService 
     ]; 
    }); 

    it('should return response when subscribed to postRequest', 
     inject([HttpService], (httpService: HttpService) => { 

      httpService.postRequest().subscribe((res) => { 
       expect(res.text()).toBe('hello raja'); 
      }); 
    })); 
}); 

這些都是我的因果報應控制檯錯誤:

28 06 2016 14:33:32.067:ERROR [Chrome 51.0.2704 (Mac OS X 10.11.4) | Http Service Test | should return response when subscribed to postRequest]: TypeError: Cannot read property 'getCookie' of null 
    at CookieXSRFStrategy.configureRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36568:81) 
    at XHRBackend.createConnection (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:36583:28) 
    at httpRequest (http://localhost:9876/absolute/var/folders/vy/18sb1wqs60g734bhr75cw9_r0000gn/T/9b9439f5f9c1590d3052594bcae9e877.browserify?26719cf22e6406ebc638b6b187c777666dcc5698:37476:20) 
+1

如果你正在測試超出了你的類的界限,達到其他外部服務不是一個單元測試,可能你想要一個集成測試。 – Sergio

+0

通過單元測試框架構建集成測試是合法的。評論員請提供答案,而不是單元測試和模擬。 – ZZZ

回答

2

您需要首先爲模擬HTTP後端配置提供:

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

然後你可以使用模擬後端是這樣的:如果你想

mockBackend.connections.subscribe(
    (connection: MockConnection) => { 
    if (connection.request.url === 'file1.json') { 
     // Simulate an error 
     var err = new ResponseError(); 
     err.status = 404; 
     connection.mockError(<Error>err); 
    } else { 
     // Simulate a successful response 
     connection.mockRespond(new Response(
     new ResponseOptions({ 
      body: ['i love angular2'] 
     }))); 
    } 
    }); 

httpService.postRequest().subscribe((res:Respsone) => { 
    expect(res.text()).toBe('hello raja'); 
}); 

編輯

要使用真實的連接進行測試,請僅使用傳統的HTTP_PROVIDERS:

describe('HttpService Tests',() => { 
    beforeEachProviders(() => { 
    return [ 
     HTTP_PROVIDERS, 
     HttpService 
    ]; 
}); 

EDIT1

由於您的調用是異步的,你可以使用async

it('should return response when subscribed to postRequest', 
    async(inject([HttpService], (httpService: HttpService) => { 

     httpService.postRequest().subscribe((res) => { 
      expect(res.text()).toBe('hello raja'); 
     }); 
}))); 
+0

好的,我用你的回覆中的新代碼更新了我的問題。你能確認這個工作嗎? (我仍然在業障中遇到捆綁錯誤) – nottinhill

+0

你使用哪個版本的Angular2?也許你可以使用'async' ...我相應地更新了我的答案 –

+0

最新版本的angular2。(RC1 2.0.0)我非常感謝你的幫助!我現在會測試你的建議。另請參閱http://stackoverflow.com/questions/34987391/jasmine-gives-cannot-read-property-getxhr-of-null-for-angular-2-unit-test – nottinhill

1

https://angular.io/docs/ts/latest/api/http/testing/MockBackend-class.html

import {BaseRequestOptions, Http} from '@angular/http'; 
import {MockBackend} from '@angular/http/testing'; 
it('should get some data', inject([AsyncTestCompleter], (async) => { 
    var connection; 
    var injector = Injector.resolveAndCreate([ 
    MockBackend, 
    {provide: Http, useFactory: (backend, options) => { 
     return new Http(backend, options); 
    }, deps: [MockBackend, BaseRequestOptions]}]); 
    var http = injector.get(Http); 
    var backend = injector.get(MockBackend); 
    //Assign any newly-created connection to local variable 
    backend.connections.subscribe(c => connection = c); 
    http.request('data.json').subscribe((res) => { 
    expect(res.text()).toBe('awesome'); 
    async.done(); 
    }); 
    connection.mockRespond(new Response('awesome')); 
})); 

https://angular.io/docs/ts/latest/api/http/testing/MockConnection-class.html

var connection; 
backend.connections.subscribe(c => connection = c); 
http.request('data.json').subscribe(res => console.log(res.text())); 
connection.mockRespond(new Response(new ResponseOptions({ body: 'fake response' }))); //logs 
'fake response' 
+1

不,不,我不明顯不想嘲笑...; D – nottinhill

+4

那麼問題是什麼?如果你不嘲笑'Http',那麼它不是一個單元測試,而是一個集成測試。 –

+0

我的代碼有一些基本的TypeScript/Angular2錯誤理解。我不知道哪個。我可以爲你準備好這個。 – nottinhill