簡體   English   中英

在使用 TestBed 創建模擬組件之前注入數據 - angular 中的單元測試 4

[英]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;

ngOnInitDeviceMarkerComponent中使用變量,我無法在不初始化變量的情況下創建組件。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM