angular: MockBackend.createConnection throws Exception

  • I’m submitting a bug in core Class MockBackend.ts
  • bug report

According to code example in Http.ts

Current behavior Using Http with MockBackend in tests, throws Exception

Error: createConnection requires an instance of Request, got [object Object]

Looks like the problem is between Http and MockBackend

Expected/desired behavior

  • **If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal Example:
import { BaseRequestOptions,  Response, ResponseOptions, Http} from '@angular/http';
import {provide, ReflectiveInjector} from '@angular/core';
import {MockBackend} from '@angular/http/testing';
import {it,  describe} from '@angular/core/testing';

describe('MockBackend: TestService', () => {
    it('should return response when subscribed to getItems', () => {
        let injector = ReflectiveInjector.resolveAndCreate([
            MockBackend, BaseRequestOptions,
            provide(Http, {
                useFactory: (backend, options) => {
                    return new Http(backend, options);
                }, deps: [MockBackend, BaseRequestOptions]
            }),
            provide(NanaDal, {
                useFactory: (http: Http) => {
                    return new NanaDal(http);
                },
                deps: [Http]
            }),
        ]);
        let backEnd: MockBackend = injector.get(MockBackend);

        backEnd.connections.subscribe((data: MockConnection) => {
            expect(data.request.url).toContain('service/126');
            data.mockRespond(new Response(new ResponseOptions({ body: { NavigateID: 1, NavigateName: 'name1' } })));
        });

        let testService: NanaDal = injector.get(NanaDal);

        expect(testService instanceof (NanaDal)).toBe(true);
        expect(NanaDal.getInstance()).toEqual(testService);
        testService.setFactory('service', 126);

        testService.getItems().subscribe((res: Navigation) => {
            expect(res).toEqual({ NavigateID: 1, NavigateName: 'name1' });
        });
    });
});

Http calls to MockBackend.createConnection and throws Exception.

mock_backend.ts

createConnection(req: Request): MockConnection {
    if (!isPresent(req) || !(req instanceof Request)) {
      throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
    }

more specific: req instanceof Request returns false

  • What is the expected behavior? Expected to NOT throw exception.
  • What is the motivation / use case for changing the behavior? Current code does not allows to provide any fakes for Http class, so needed change in function preconditions or add instantiated parameter on caller function in Http.ts
function httpRequest(backend: ConnectionBackend, request: Request): Observable<Response> {
  return backend.createConnection(request).response;
}
  • Please tell us about your environment: VS Code on Windows 10 x64
  • Angular version: 2.0.0-rc.1
  • Browser: [Chrome 51 ]
  • Language: [ TypeScript 1.8.10 | ES5 ]

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 22 (1 by maintainers)

Most upvoted comments

Could someone find a soultion for use it with packUmd?

The workaround we used was to hack into the SystemJS configuration file so that it always uses the packIndex for http module:

  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
    'testing'
  ];

  var ngIndexPackageNames = [
    'http'
  ];

  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }

  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' };
  };

  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;

  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  ngIndexPackageNames.forEach(packIndex);

It seems that there is a problem with umd packaging.

If you use the packIndex, it works. With the packUmd no…

//var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Not working
var setPackageConfig = packUmd;
// Working
var setPackageConfig = packIndex;

I opened an issue for this problem: https://github.com/angular/angular/issues/9180

😮 @templth , it’s an Injector. ok, i’ll do it tomorrow ASAP 👌

I think I’m seeing the same problem. The issue is in the test code, not in the implementation. When you try and make a request with the mocked Http service, you get this error.

import { describe, inject, it, beforeEachProviders } from '@angular/core/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
describe('When recieving an OK response', () => {
        beforeEachProviders(() => [
            NanaDal,
            MockBackend,
            BaseRequestOptions,
            {
                provide: Http,
                useFactory: (backend, options) => new Http(backend, options),
                deps: [MockBackend, BaseRequestOptions]
            }]
        );

        it('returns the items', inject([NanaDal, MockBackend], (nanaDal:NanaDal, mockBackEnd:MockBackend) => {
            mockBackEnd.connections.subscribe((connection:MockConnection) => {
             connection.mockRespond(new Response(new ResponseOptions({body: JSON.stringify({id: 666})})));
            });

            return nanaDal.getItems(); // <= this line throws instead of making a request with themock backend
        }));
    });