在使用TestBed创建模拟组件之前注入数据 - 以角度4进行单元测试

时间:2017-09-27 12:35:39

标签: angular jasmine karma-runner

我想在运行此代码之前将数据注入DeviceMarkerComponent

let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...

fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;

DeviceMarkerComponent使用ngOnInit中的变量,我无法在不初始化变量的情况下创建组件。 NgOnInit在调用TestBed.CreateComponent时触发并导致错误,因此我必须设置这些变量或修改我正在测试的代码:(

enter image description here

1 个答案:

答案 0 :(得分:0)

在创建组件之前,您需要配置测试平台。在配置中,您可以设置组件正在使用的内容以及通过间谍程序的导入,声明等。

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