测试角度树组件时未定义treeModel

时间:2019-05-08 02:27:54

标签: angular unit-testing jasmine spy

我正在与angular-tree-component合作,以角度显示无状态组件中的类别树。目前,我已经启动并运行了该组件,现在该进行一些单元测试了。我遇到了一个问题,因为我想测试一个执行执行treeModel的方法update()的函数,该函数是公开angular-tree-component的API的tree组件的属性。 (请参阅文档here)。

我的名为updateTree()的函数仅在treeModel上运行update(),如下所示:

export class CategoryTreeComponent implements AfterViewInit {

  @ViewChild('tree') treeComponent: TreeComponent;
  treeModel: TreeModel;

  constructor() {
  }

  ngAfterViewInit() {
    debugger;
    this.treeModel = this.treeComponent.treeModel;
  }

  updateTreeFn() {
    this.treeModel.update();
  }

}

因此,我编写了如下所示的单元测试。

it('should call update method of treeModel', () => {    
  component.ngAfterViewInit();
  fixture.detectChanges();
  const spy = spyOn(component.treeModel, 'update');
  component.updateTree();
  expect(spy).toHaveBeenCalled();  
});

问题在于treeModel始终是undefined。我注意到treeModel是TreeComponent类上TreeModel类型的类属性,而update是TreeModel对象的方法。可能这就是为什么我会收到该错误。

关于如何测试该更新方法并识别treeModel对象进行监视的任何想法。

1 个答案:

答案 0 :(得分:0)

最近我遇到了类似的问题,将测试包装在fakeAsync区域中可以解决问题:

it('should call update method of treeModel', fakeAsync(() => {    
  component.ngAfterViewInit();
  tick(100);
  fixture.detectChanges();
  const spy = spyOn(component.treeModel, 'update');
  component.updateTree();
  tick(100);
  expect(spy).toHaveBeenCalled();  
}));

但是我不确定要监视treeModel的方法...

相关问题