如何修复Angular 2中的“无法读取null的注入器属性”bug?
问题描述:
This question描述如何在beforeEachProviders
函数不推荐使用后更新Angular 2。如何修复Angular 2中的“无法读取null的注入器属性”bug?
不过话说做到这一点,我得到的错误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);
}));
});
答
addProviders也已经过时,是有利于测试床的。
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
我得到一个错误'无法设置基地供应商,因为它,当我这样做已经called',但测试工作,当我移动'initTestEnvironment'打电话到' beforeEach'(如果你想运行多个测试,必须在'afterEach'中执行'TestBed.resetTestEnvironment')。测试工作,但奇怪的是,这是事实。我做错了什么? –
每次测试完成后调用initTestEnvironment和resetTestEnvironment都可以,但理想情况下,您只需在所有测试中调用init一次。 Webpack示例显示将其放入业务填充文件中。 https://angular.io/docs/ts/latest/guide/webpack.html – Dave