【问题标题】:Angular2: Can't test component with templateUrl using TestBed.compileComponent()Angular2:无法使用 TestBed.compileComponent() 使用 templateUrl 测试组件
【发布时间】:2016-10-03 15:57:44
【问题描述】:

我正在尝试了解 Angular2 测试 API 的基础知识,而 TestBed.compileComponents() 让我抓狂。要么我这样称呼它:

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

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

要么这样(如documentation 中所述):

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

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

然后我得到错误: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

【问题讨论】:

  • 如果在 compileComponents 编译组件时调用 done() 会发生什么,即在传递给 then() 的函数内部?
  • @JBNizet 同样的事情,我得到一个未定义的组件。顺便说一句,很棒的 angular2 书
  • 你能展示你的组件的代码和模板吗?

标签: unit-testing angular karma-jasmine


【解决方案1】:

试试这个:

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

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

        fixture = TestBed.createComponent(FooComponent);
        fixture.detectChanges();
    });

这里不需要异步。

【讨论】:

  • Asynchronicity 用于等待 .compileComponents() 结束其编译工作,您在示例中没有使用。甚至已知的 Angular2 文档都指出你不需要它使用 webpack 如果我不需要它,我会收到错误 please call TestBed.compiledComponents
  • 已经有一段时间了,但我重新开始测试应用程序。你的解决方案对我有用,你是对的,这里不需要异步。迟到的谢谢:)
【解决方案2】:

试试这个:

beforeEach( async( () => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  })
  .compileComponents().then( () => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance();
  });
}));

【讨论】:

    【解决方案3】:

    我遇到了同样的问题。我认为问题出在您的组件模板中。如果您使用其他一些自定义组件,但没有在测试模块中指定它们,那么 Angular 会抛出该错误(当然非常具有误导性)。

    那么,你的下一个选择:

    1. 在 TestBed 配置中指定所有使用的组件
      1. 作为一种变体,您可以通过相应的模拟来存根所有组件。
    2. 使用 NO_ERRORS_SCHEMA 进行浅层测试,如此处所述https://angular.io/docs/ts/latest/guide/testing.html#shallow-component-test

    【讨论】:

      【解决方案4】:

      只是为了建立 Zonkil 的答案,我发现要让它工作,我必须实际设置夹具并在测试中创建组件。例如:

      it('test the component renders',() => {      
              fixture = TestBed.createComponent(AppComponent);
              comp = fixture.componentInstance; 
              fixture.detectChanges();
              expect(comp).toBeDefined();
          });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-08
        • 1970-01-01
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多