我正在使用angular-tree-component在angular中显示一个无状态组件中的类别树。目前,我已经启动并运行了组件,是时候进行一些单元测试了。我遇到了一个问题,因为我想测试一个执行treeModel的方法update()的函数,该方法是树组件的属性,它公开了角度树组件的API。(请参阅文档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对象的方法。也许,这就是我得到这个错误的原因。
任何关于如何测试该update方法的想法都会被调用,并识别treeModel对象来监视它。
发布于 2020-01-21 22:43:30
最近,我遇到了类似的问题,将我的测试包装为在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的方法。
https://stackoverflow.com/questions/56032721
复制相似问题