【问题标题】:Angular unit test fails because of component in constructor.由于构造函数中的组件,Angular 单元测试失败。
【发布时间】:2018-09-04 15:45:00
【问题描述】:

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

  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 中,所以这不是问题。我也尝试将它添加到提供者数组中。但这只是将其移动到无法添加到提供程序数组的角度渲染器中。我还在CoreComponent 的@component 标记之前添加了一个@injectable() 标记,但这并没有改变我的测试失败。

我尝试使用@host() 获取它,但它会引发错误。我也尝试使用Injector 来获取它,但这也会引发错误。这些是 4 个组件,它们使用 CoreComponent 作为 var 从它们那里获取一些信息,但它们会使测试失败。我所有的其他测试都通过了超过 80 次测试。只是这 4 个不起作用,因为它们试图获取在 CoreComponent 中定义的属性。

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

【问题讨论】:

  • 这似乎是一个愚蠢的问题,但 CoreComponent 是实际的组件还是服务?
  • 是的,它是一个组件,它实际上是一个 ngprime 模板的基本代码,所以你可以在这里查看它:github.com/primefaces/primeng-blueprint/blob/master/src/app/…
  • 我只是将其称为 all core 而不是 app,因为我在 app.component.ts 中处理其他内容

标签: javascript angular testing components karma-runner


【解决方案1】:

要修复此错误,请使用 @host 和 @optional 装饰器。这告诉编译器寻找它,但如果没有提供它就不需要:

  constructor(
    @Host() @Optional() public core: CoreComponent,
  ) {
    //
  }

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2017-09-15
    • 1970-01-01
    • 2018-09-14
    • 2021-04-26
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多