Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在单元测试中模拟HttpResponse Angular2_Angular_Unit Testing_Jasmine_Mocking - Fatal编程技术网

在单元测试中模拟HttpResponse Angular2

在单元测试中模拟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

在其中一个单元测试中,我需要模拟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.connections应该只存在于mock实现中

你知道为什么这个财产不存在吗


问候

我发现我通过测试的东西有问题-它实际上是一个空对象

我发现我通过测试的东西有问题-它实际上是一个空对象

mockBackend.http._backend.connections