Angular 2.0.0-rc.1:如何测试视图或内容上的元素(例如@ViewChildren、@ContentChildren)

Angular 2.0.0-rc.1:如何测试视图或内容上的元素(例如@ViewChildren、@ContentChildren),angular,angular2-testing,Angular,Angular2 Testing,我有一个组件,它从服务中获取数据,该服务在视图上创建子对象。这些子项仅在创建视图时可用。在我下面的示例中,视图在到达其测试之前没有创建,因此测试2失败 组成部分: @Component({ selector: 'component-to-test', providers: [Service], directives: [NgFor, ChildComponent], template: ` <child [data]="childData" *ngFor="let

我有一个组件,它从服务中获取数据,该服务在
视图上创建子对象。这些子项仅在创建
视图时可用。在我下面的示例中,
视图
在到达其测试之前没有创建,因此测试2失败

组成部分:

@Component({
  selector: 'component-to-test',
  providers: [Service],
  directives: [NgFor, ChildComponent],
  template: `
    <child [data]="childData" *ngFor="let childData of data"></child>
})

export class ComponentToTest implements OnInit {
  @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
  private data: any;

  public ngOnInit() {
    this.getData();
  }

  private getData() {
    // async fetch data from a service
  }
}

测试1通过,测试2失败。如何测试初始化
视图
内容
后创建的内容?

我将利用
异步
功能:

it('should initialise children', async(inject([ComponentToTest], (component: ComponentToTest, service: Service) => {
  return service.getData().toPromise().then(() => {
    expect(component.children).toBeDefined();
  });
})));
从文件中:

在异步测试区域中包装测试函数。此区域内的所有异步调用完成后,测试将自动完成。可用于包装注入调用


注入组件只会创建组件类的实例,但不会调用生命周期回调,也不会创建视图

您需要改用
TestComponentBuilder

describe('ComponentToTest', () => {
  let component: ComponentToTest;
  beforeEach(async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb.createAsync(ComponentToTest).then((fixture: ComponentFixture<ComponentToTest>) => {
      fixture.detectChanges();
      component = fixture.componentInstance;
      // component.ngOnInit(); // called by `fixture.detectChanges()`
    });
  })));

  it('should initialise children', () => {
    expect(component.children).toBeDefined();
  });
});
description('ComponentToTest',()=>{
let组件:组件测试;
beforeach(异步(注入([TestComponentBuilder],(tcb:TestComponentBuilder)=>{
tcb.createAsync(ComponentToTest).then((fixture:ComponentFixture)=>{
fixture.detectChanges();
组件=fixture.componentInstance;
//component.ngOnInit();//由`fixture.detectChanges()调用`
});
})));
它('应该初始化子项',()=>{
expect(component.children.toBeDefined();
});
});
为了确保测试不会在所有异步执行完成之前结束,还可以使用Thierry已经提到的
async()

describe('ComponentToTest', () => {
  let component: ComponentToTest;
  beforeEach(async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    tcb.createAsync(ComponentToTest).then((fixture: ComponentFixture<ComponentToTest>) => {
      fixture.detectChanges();
      component = fixture.componentInstance;
      // component.ngOnInit(); // called by `fixture.detectChanges()`
    });
  })));

  it('should initialise children', () => {
    expect(component.children).toBeDefined();
  });
});