2017-05-08 76 views
0

在單元測試中,我需要模擬一個HTTP響應的一個,我覺得我就是這麼做的經書,但似乎不管什麼原因,我收到以下異常:嘲諷的HttpResponse Angular2在單元測試

‘TypeError: Cannot read property 'subscribe' of undefined’ 

這是在參考該行:

mockBackend.connections.subscribe((connection) 


describe('ServiceUnderTest',() => { 
    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     providers: [ServiceUnderTest, MockBackend, BaseRequestOptions, 
     { provide: XHRBackend, useExisting: MockBackend }, 
     { 
      provide: Http, 
      deps: [XHRBackend, BaseRequestOptions], 
      useFactory: (backend, options) => { return new Http(backend, options); }, 
     }], 
     imports: [HttpModule], 
    }); 
    }); 

it('should return array', async(inject([ServiceUnderTest, MockBackend], (service: ServiceUnderTest, mockBackend) => { 

    const mockResponse: any = { 
     data: [ 
     { 'code': '123', 'desc': 'ab' }, 
     { 'code': '345', 'desc': 'cd' },   
     ], 
    }; 

    // Line which throws error 
    mockBackend.connections.subscribe((connection) => { 
     connection.mockRespond(new Response(new ResponseOptions({ 
     body: JSON.stringify(mockResponse), 
     }))); 
    }); 

    service.getMyGear().subscribe(result => { 
     let fishingGears: Array<any> = result; 
     expect(fishingGears.length).toBe(3); 
     expect(fishingGears[0].desc).toBe('Pots'); 
    }); 

以下的解決方法解決了這個問題:

mockBackend.http._backend.connections 

根據文檔屬性:mockBackend.connections應該只存在於模擬實現中。

任何想法爲什麼這個屬性不存在?

問候!

回答

0

我發現一個問題,我已經傳遞給測試 - 它實際上是一個空對象!