【问题标题】:Mocking HttpResponse Angular2 in a unit test在单元测试中模拟 HttpResponse Angular2
【发布时间】: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


    【解决方案1】:

    我发现我通过测试的内容存在问题 - 它实际上是一个空对象!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 2016-04-18
      • 2019-12-13
      • 2017-03-12
      相关资源
      最近更新 更多