2016-08-23 47 views
3

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

回答

5

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

+0

我得到一個錯誤'無法設置基地供應商,因爲它,當我這樣做已經called',但測試工作,當我移動'initTestEnvironment'打電話到' beforeEach'(如果你想運行多個測試,必須在'afterEach'中執行'TestBed.resetTestEnvironment')。測試工作,但奇怪的是,這是事實。我做錯了什麼? –

+0

每次測試完成後調用initTestEnvironment和resetTestEnvironment都可以,但理想情況下,您只需在所有測試中調用init一次。 Webpack示例顯示將其放入業務填充文件中。 https://angular.io/docs/ts/latest/guide/webpack.html – Dave

相關問題