如何修复"无法读取null"的注入器属性Angular 2中的错误?

时间:2016-08-23 15:58:55

标签: unit-testing angular

This question介绍了在弃用beforeEachProviders函数后如何更新Angular 2。

但是这样做了,我收到错误Cannot read property 'injector' of null

我的测试相对基础:

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);
    }));
});

1 个答案:

答案 0 :(得分:5)

addAdviders也被弃用,有利于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