由于构造函数中的组件,角度单元测试失败。

时间:2018-09-04 15:45:01

标签: javascript angular testing components karma-runner

我有一个使用此的构造函数:

  constructor(
    public core: CoreComponent,
  ) {
   //
  }

但是当我尝试使用这样的测试用例测试这些组件时:

describe('CoreSubMenuComponent', () => {
  let component: CoreSubMenuComponent;
  let fixture: ComponentFixture<CoreSubMenuComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        TestingModule.forRoot(),
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoreSubMenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我得到一个空注射器错误:

Error: StaticInjectorError(DynamicTestModule)[CoreSubMenuComponent -> CoreComponent]: 
  StaticInjectorError(Platform: core)[CoreSubMenuComponent -> CoreComponent]: 
    NullInjectorError: No provider for CoreComponent!

它被导入到testingModule中,所以这不是问题。我还尝试将其添加到providers数组。但这只是将其移动到无法添加到providers数组的角度渲染器中。我还在@injectable()中的@component标记之前添加了CoreComponent标记,但是它不会改变测试失败的情况。

我尝试使用@host()来获取它,但是它引发了错误。我也尝试使用Injector来获取它,但这也会引发错误。这是4个使用CoreComponent作为变量的组件,以从中获取一些信息,但它们使测试失败。我的所有其他测试都通过了80多个测试,一切顺利。仅这4个无效,因为它们试图获取CoreComponent中定义的属性。

有人知道我如何用实例引用此组件,以便我的测试通过?

1 个答案:

答案 0 :(得分:0)

要解决此错误,请使用@host和@Optional装饰器。这告诉编译器寻找它,但是如果没有提供它则不需要:

  constructor(
    @Host() @Optional() public core: CoreComponent,
  ) {
    //
  }
相关问题