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应该只存在于模拟实现中。
任何想法为什么这个属性不存在?
问候!