繁体   English   中英

在单元测试中模拟HttpResponse Angular2

[英]Mocking HttpResponse Angular2 in a unit test

在一个单元测试中,我需要模拟一个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

根据documentation属性:mockBackend.connections仅应存在于模拟实现中。

有什么想法为什么这个属性不存在?

问候!

我发现我传递给测试的内容存在问题-实际上这是一个空对象!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM