【发布时间】:2017-05-08 11:57:36
【问题描述】:
在其中一个单元测试中,我需要模拟一个 http 响应,我想我是按照书本做的,但似乎无论出于何种原因,我都会遇到以下异常:
‘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 应该只存在于模拟实现中。
任何想法为什么这个属性不存在?
问候!
【问题讨论】:
标签: angular unit-testing jasmine mocking