Angular2:无法使用TestBed.compileComponent()使用templateUrl测试组件

the*_*ana 5 unit-testing karma-jasmine angular

我试图获得Angular2测试API和TestBed.compileComponents()的基础知识让我疯狂.我要么像这样称呼它:

beforeEach( done => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  })
  .compileComponents().then( () => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance();
  });
  done();
});
Run Code Online (Sandbox Code Playgroud)

然后我的组件在我的测试中未定义(我相信,因为compileComponent是异步的,测试在我的var组件获取值之前运行)

要么那样(如文档中所述):

beforeEach( async(() => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  }))
  .compileComponents();

beforeEach( () => {
  fixture = TestBed.createComponent(HomeComponent);
  component = fixture.componentInstance();
});
Run Code Online (Sandbox Code Playgroud)

但后来我得到了错误: This test module uses the component HomeComponent which is using a "templateUrl", but they were never compiled. Please call "TestBed.compileComponents" before your test.

有人可以帮忙吗?

忘了说我使用webpack和RC6

R2C*_*2C2 5

尝试这个:

describe('FooComponent', function () {
    let fixture: ComponentFixture<FooComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [FooComponent]
        });

        fixture = TestBed.createComponent(FooComponent);
        fixture.detectChanges();
    });
Run Code Online (Sandbox Code Playgroud)

这里不需要异步。

  • 使用异步性是为了等待 .compileComponents() 结束其编译工作,您在示例中没有使用它。即使已知的 Angular2 文档也声明你不需要使用 webpack,如果不需要,我会收到错误“请调用 TestBed.compiledComponents” (2认同)