Search code examples
testingangularangular2-testing

Angular 2 beforeEachProviders fail with Injector in tests


When I try to pass Injector to the beforeEachProviders in tests I get the following error.

Failed: Cannot resolve all parameters for 'Injector'(?, ?, ?, ?, ?).
Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Injector' is decorated with Injectable.

The code I use

import { Injector } from 'angular2/core';

describe(() => {
  beforeEachProviders(() => [Injector]);
});

What is missing? What should I give to the providers to be able to instantiate it?


Solution

  • I don't think that you need to configure Injector in your providers for the test. An instance of this class can be directly injected into your test...

    Here is what I have in one of my tests (no "explicit" provider for Injector) and I'm able to inject it into a test later:

    import {it, describe, expect, beforeEach, inject, beforeEachProviders} from 'angular2/testing';
    import {HTTP_PROVIDERS, XHRBackend, Response, ResponseOptions} from 'angular2/http';
    import {MockBackend, MockConnection} from 'angular2/http/testing';
    import {provide, Injector} from 'angular2/core';
    import {HttpService} from "./http-service";
    
    describe('HttpService Tests', () => {
      beforeEachProviders(() => {
        return [
          HTTP_PROVIDERS,
          provide(XHRBackend, { useClass: MockBackend }),
          HttpService
        ];
      });
    
      it('Should return a list of dogs', inject(
             [XHRBackend, HttpService, Injector],
             (mockBackend, httpService, injector) => {
        console.log(injector); // <----- Not null
      });
    });