如何使用`entryComponents`对组件进行浅层测试?

Man*_*uel 13 angular

例如,假设您有以下组件:

import { Another } from "./Another";
@Component({
    entryComponents: [
        Another
    ]
})
export class App {}
Run Code Online (Sandbox Code Playgroud)

即使在使用时NO_ERRORS_SCHEMA我仍然必须包含Another作为测试声明的一部分:

import { ComponentFixture, TestBed } from "@angular/core/testing";
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { App } from "./App";
import { Another } from "./Another";

describe("App", () => {
  let comp: App;
  let fixture: ComponentFixture<App>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ App, Another ],
      schemas: [ NO_ERRORS_SCHEMA ]
    });
    fixture = TestBed.createComponent(App);
    comp = fixture.componentInstance;
  });

  it("can load instance", () => {
    expect(comp).toBeTruthy();
  });

});
Run Code Online (Sandbox Code Playgroud)

kam*_*psj 11

他们计划添加EntryComponents到测试模块接口.请参阅问题:https://github.com/angular/angular/issues/10760

有关当前的解决方法,请参阅Angular Material库,请参阅https://github.com/angular/material2/blob/master/src/lib/dialog/dialog.spec.ts#L479.

基本上,他们动态创建一个真实的模块,然后导入它进行测试.

// Create a real (non-test) NgModule as a workaround for
// https://github.com/angular/angular/issues/10760
const TEST_DIRECTIVES = [
  ComponentWithChildViewContainer,
  PizzaMsg,
  DirectiveWithViewContainer,
  ContentElementDialog
];

@NgModule({
  imports: [MdDialogModule],
  exports: TEST_DIRECTIVES,
  declarations: TEST_DIRECTIVES,
  entryComponents: [ComponentWithChildViewContainer, PizzaMsg, ContentElementDialog],
})
class DialogTestModule { }
Run Code Online (Sandbox Code Playgroud)

现在你可以使用了 DialogTestModule

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [MdDialogModule.forRoot(), DialogTestModule]
      ...
Run Code Online (Sandbox Code Playgroud)