3

This question describes how to update Angular 2 after the beforeEachProviders function was deprecated.

But having done that, I get the error Cannot read property 'injector' of null

My test is relatively basic:

import { inject, addProviders } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('Foo', () => {
    beforeEach(() => {
        addProviders([{
            provide: MyComponent,
            useClass: MyComponent
        }]);
    });

    it('foo', inject([MyComponent], (e: MyComponent) => {
        expect(true).toEqual(true);
    }));
});
Community
  • 1
  • 1
A. Duff
  • 4,097
  • 7
  • 38
  • 69

1 Answers1

5

addProviders is also deprecated is favor of TestBed.

import { TestBed, async } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { MyComponent } from './my.component';

// This should only be called once.
TestBed.initTestEnvironment(
    BrowserDynamicTestingModule, platformBrowserDynamicTesting());

describe('Foo', () => {
    beforeEach(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
      });
      TestBed.compileComponents();
    });

    it('foo', async(() => {
        let fixture = TestBed.createComponent(MyComponent);
        fixture.detectChanges();
        expect(true).toEqual(true);
    }));
});

Angular2 RC5

Dave
  • 3,171
  • 1
  • 25
  • 23
  • I get an error ` Cannot set base providers because it has already been called` when I do it this way, but the tests work when I move the `initTestEnvironment` call to the `beforeEach` (having to do `TestBed.resetTestEnvironment` in an `afterEach` if you want to run more than one test as a result). The tests work, although strange that this is the case. Am I doing anything wrong? – A. Duff Aug 24 '16 at 15:02
  • Calling initTestEnvironment before and resetTestEnvironment after each test is fine, but ideally you'd just call init once across all your tests. The Webpack example shows putting it in the karma shim file. https://angular.io/docs/ts/latest/guide/webpack.html – Dave Aug 24 '16 at 22:58