2016-04-15 104 views
2

我嘗試用DI測試某個組件。我在尋找像堆棧/論壇等常見資源,但沒有正確的答案我的問題(我找不到)。問題與角度2測試DI

當我嘗試提供模擬依賴關係時,我得到錯誤:令牌必須定義 這是什麼?我如何提供模擬依賴? (在提供的組件中存在一些下一級別的依賴關係 - 從httpconfig,所以我可以真實地創建它(因爲他失敗了自己的依賴關係......而且我認爲我必須嘲笑這種依賴關係)

有我的測試

import {provide} from 'angular2/core'; 

import {setBaseTestProviders} from 'angular2/testing'; 
import { 
TEST_BROWSER_PLATFORM_PROVIDERS, 
TEST_BROWSER_APPLICATION_PROVIDERS 
} from 'angular2/platform/testing/browser'; 

import { beforeEach,beforeEachProviders,describe,expect, 
provide, 
it, 
inject, 
injectAsync, 
TestComponentBuilder, 
AsyncTestCompleter} from 'angular2/testing'; 


import {HTTPPatientsListService} from '../../shared/http_services/http_patients_list.service'; 
import {PatientsListComponent} from './patients_list.component'; 

class MockClass {} 

describe('Patients list Tests',() => { 
    beforeEachProviders(() => [ 
    provide(HTTPPatientsListService, {useClass: MockClass}) 
    ]); 

    it('Should defined recentPatientData ', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => { 
    return tcb.createAsync(PatientsListComponent).then((componentFixture: ComponentFixture) => { 
     const element = componentFixture.nativeElement; 
     componentFixture.detectChanges(); 
    }); 
    })); 


}); 

有我的組件的部分(僅限於一部分。它是正確的工作,買他太長時間)

@Component({ 
    selector: 'cgm_patients_list', 
    templateUrl: `${MODULE_PATH}/patients_list.component.html`, 
    styleUrls: [`..${MODULE_PATH}/patients_list.component.css`], 
    pipes: [SearchPipe], 
    providers: [HTTPPatientsListService], 
    directives: [PatientsListDetailComponent] 
}) 

export class PatientsListComponent implements OnInit { 
    public recentPatientData; 

    private pipedPatientsData; 

    constructor(
    private patientsListService: HTTPPatientsListService) { 

    } 

感謝您的幫助...

P.S.錯誤是:

Chrome 49.0.2623 (Windows 7 0.0.0) Patients list Tests Should defined recentPatientData FAILED 
     Failed: Token must be defined! 
     Error: Token must be defined! 
      at new BaseException (D:/nucleous/client/src/www/node_modules/angular2/bundles/angular2.dev.js:7521:21) 
+0

@君特Zöchbauer的答案是正確的。另外我會建議檢查https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/它有很好的例子。 – echonax

回答

1

你需要重寫測試組件的供應商

return tcb 
.overrideProviders(PatientsListComponent, [provide(HTTPPatientsListService, {useClass: MockClass})]) 
.createAsync(PatientsListComponent) 
.then((componentFixture: ComponentFixture) => { 

參見https://angular.io/docs/ts/latest/api/testing/TestComponentBuilder-class.html

+0

嗨Gunter。很高興見到你!我嘗試使用你的提示,但得到了新的錯誤: * TypeError:tcb.createAsync(...)。overrideProviders不是函數* 是什麼意思? – Velidan

+0

已解決:) createAsync必須在覆蓋提供程序之後。感謝Gunter再次爲您提供幫助和時間! _return tcb.overrideProviders(PatientsListComponent [provide(HTTPPatientsListService,{useClass:MockClass})]) .createAsync(PatientsListComponent)_ – Velidan

+0

Thanks!固定。複製粘貼錯誤: - / –