我嘗試用DI測試某個組件。我在尋找像堆棧/論壇等常見資源,但沒有正確的答案我的問題(我找不到)。問題與角度2測試DI
當我嘗試提供模擬依賴關係時,我得到錯誤:令牌必須定義 這是什麼?我如何提供模擬依賴? (在提供的組件中存在一些下一級別的依賴關係 - 從http和config,所以我可以真實地創建它(因爲他失敗了自己的依賴關係......而且我認爲我必須嘲笑這種依賴關係)
有我的測試
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)
@君特Zöchbauer的答案是正確的。另外我會建議檢查https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/它有很好的例子。 – echonax