【问题标题】:Injecting data before creating mock component with TestBed - unit testing in angular 4在使用 TestBed 创建模拟组件之前注入数据 - 角度 4 中的单元测试
【发布时间】:2017-09-27 12:35:38
【问题描述】:

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

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

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

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

【问题讨论】:

  • 知道它抛出了什么错误会很有帮助。 DeviceMarkerComponent 在其构造函数中是否存在您未提供的依赖项?
  • 我添加了图片
  • 没关系,我已经解决了,我会在晚上添加解决方案

标签: angular jasmine karma-runner


【解决方案1】:

您需要在创建组件之前配置测试平台。在配置中,您可以设置组件正在使用的导入、声明等以及传递 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;
});

还有一个类型别名可用于测试台配置,这很有帮助。
https://angular.io/api/core/testing/TestModuleMetadata

【讨论】:

  • 是的,但它仍然在这里,所以不妨回答一下。 ;)
【解决方案2】:
    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 类下的注入方法document

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多