[英]Injecting data before creating mock component with TestBed - unit testing in angular 4
I would like to inject data to DeviceMarkerComponent
before running this:我想在运行之前向
DeviceMarkerComponent
注入数据:
let component: DeviceMarkerComponent;
let fixture: ComponentFixture<DeviceMarkerComponent>;
...
fixture = TestBed.createComponent(DeviceMarkerComponent);
component = fixture.componentInstance;
DeviceMarkerComponent
uses variables in ngOnInit
and I can't create the component without initializing the variables. ngOnInit
在DeviceMarkerComponent
中使用变量,我无法在不初始化变量的情况下创建组件。 NgOnInit
is firing when TestBed.CreateComponent
is called and it causes error, so I have to set these variables or modify a code which I'm testing:( NgOnInit
在调用TestBed.CreateComponent
时触发并导致错误,因此我必须设置这些变量或修改我正在测试的代码:(
You need to configure the testbed before creating the component. 在创建组件之前,您需要配置测试平台。 In the configuration you can set imports, declarations, etc of what your component is using as well as pass spys.
在配置中,您可以设置组件使用的导入,声明等以及传递间谍。
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;
});
There is also a Type alias you can use for the testbed configuration that can be helpful. 您还可以将Type别名用于测试平台配置,这很有帮助。
https://angular.io/api/core/testing/TestModuleMetadata 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;
the document of inject method under the TestBedStatic class. TestBedStatic class下的注入方法文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.