在单元测试中模拟HttpResponse Angular2
在其中一个单元测试中,我需要模拟http响应,我想我是照本宣科地这么做的,但不管出于什么原因,我似乎得到了以下异常:在单元测试中模拟HttpResponse Angular2,angular,unit-testing,jasmine,mocking,Angular,Unit Testing,Jasmine,Mocking,在其中一个单元测试中,我需要模拟http响应,我想我是照本宣科地这么做的,但不管出于什么原因,我似乎得到了以下异常: ‘TypeError: Cannot read property 'subscribe' of undefined’ 这是关于这一行的: mockBackend.connections.subscribe((connection) describe('ServiceUnderTest', () => { beforeEach(() => { Tes
‘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.connections应该只存在于mock实现中
你知道为什么这个财产不存在吗
问候 我发现我通过测试的东西有问题-它实际上是一个空对象 我发现我通过测试的东西有问题-它实际上是一个空对象
mockBackend.http._backend.connections