2017-01-03 38 views
0

我嘗試與Angular2,SystemJs的MockBackends時遇到問題。我想測試我的服務方法的各種狀態,但我不斷收到錯誤(錯誤:createConnection需要一個請求的實例,得到[對象對象])。我無法從Systemjs中看到任何404s。我嘗試了直接從Angular2文檔中進行單元測試,因爲這也不起作用:錯誤:createConnection需要一個實例的請求,得到[對象對象] - Angular2,SytemJs

我還應該檢查什麼?

- 我的測試

it('should get a response',() => { 
    let connection; //this will be set when a new connection is emitted from the backend. 
    let text; //this will be set from mock response 
    let injector = ReflectiveInjector.resolveAndCreate([ 
     MockBackend, 
     BaseRequestOptions, 
     {provide: Http, useFactory: (backend, options) => { 
      return new Http(backend, options); 
     }, deps: [MockBackend, BaseRequestOptions]}]); 
    let backend = injector.get(MockBackend); 
    let http = injector.get(Http); 
    backend.connections.subscribe(c => connection = c); 
    http.request('https://jsonplaceholder.typicode.com/users').subscribe(res => { 
     text = res.text(); 
    }); 

    console.log('text: ', text); 

    connection.mockRespond(new Response({body: [{'id': 1}]})); 

    expect(text).toBeDefined(); 

}); 

- 我的服務呼叫

return this._http.get(this.url) 
      .map(res => res.json()); 

回答

0

import {ResponseOptions} from '@angular/http'; (...) connection.mockRespond(new Response(new ResponseOptions({body: [{'id': 1}]})));

響應的構造函數需要它的論點ResponseOptions包梁;-)

P.S .:幾天前更新了master分支中的越野車示例,但doc仍使用舊標籤。新樣本可以在github上找到:https://github.com/angular/angular/blob/master/modules/@angular/http/testing/mock_backend.ts

+0

Hi @E。 Hein,我根據你的帖子進行了修改,但我仍然有同樣的問題。我只改變了你推薦的行,因爲我已經有了ResponseOptions API。任何其他想法我需要看看? – Jimi

+0

早上好吉米,自己試了一下這個例子,它按預期工作:[見connection-response.spec.ts](http://plnkr.co/edit/KWBwBfByHlkFmYlKRcPW?p=preview)。你使用哪個角度版本? (不要以爲是因果報應者)PS:顯然我們生活在不同的時區^^ –

+0

我使用的是2.3.0,那肯定是問題所在。我已經升級了,似乎有什麼問題。我的測試不會因爲這個問題而運行,任何有關解決問題的想法?在XMLHttpRequest.ZoneTask.invoke(http:// localhost:9876/base/jspm_packages/npm/zone .js @ 0.7.4/dist/zone.js:293:27)[] 加載http://時出錯localhost:9876/base/process.js as「process」from http:// localhost:9 876/base/jspm_packages/npm/@ angular/compiler @ 2.4.1/testing /../ bundles/compiler.umd。 JS' – Jimi

相關問題