[英]Injecting data before creating mock component with TestBed - unit testing in angular 4
我想在運行之前向DeviceMarkerComponent
注入數據:
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
ngOnInit
在DeviceMarkerComponent
中使用變量,我無法在不初始化變量的情況下創建組件。 NgOnInit
在調用TestBed.CreateComponent
時觸發並導致錯誤,因此我必須設置這些變量或修改我正在測試的代碼:(
在創建組件之前,您需要配置測試平台。 在配置中,您可以設置組件使用的導入,聲明等以及傳遞間諜。
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
declarations: [DeviceMarkerComponent],
providers: [any providers the component uses]
imports: [any imports component uses]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
});
您還可以將Type別名用於測試平台配置,這很有幫助。
https://angular.io/api/core/testing/TestModuleMetadata
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...
const testBed = TestBed.configureTestingModule({...});
// do anything you want to do before createComponent
testBed.inject(AService).init();
testBed.compileComponents();
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
TestBedStatic class下的注入方法文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.