首页 > 解决方案 > 分配给属性的匿名函数的角度测试

问题描述

我需要测试一个 Angular 组件函数 (func1) 是否被另一个 Angular 方法中动态实例化的对象的匿名函数属性调用。有点难以理解,但让我解释一下。

我有一个导出的类,该类具有一个匿名函数作为类型的属性。像这样的东西:

export class Detail {
  id: string;
  name: string;
  onSave: () => void;
}

在我的组件中,我有一个方法可以实例化 Detail 类的对象,并为onSave调用funFn.

myFunction(item: Item){
   const detail = new Detail();
   detail.onSave= (){
     this.runFn(item); 
   }
   this.someService.doSomethingWith(details);
}

runFn(item: Item){
   ... do something cool.
}

我想测试是否在执行runFn时被调用onConfirm。所以,在我的测试用例中,我有:

it("Should calls runFn", function () {
      spyOn(Detail.prototype, 'onSave').and.callThrough();

      const mockItem = new Item();
      component.myFunction(mockItem);

      expect(component.runFn).toHaveBeenCalledWith(mockItem);
});

上面的代码不起作用,因为onSave它不是方法,而是属性。那么,我如何模拟在其中创建的实例myFunction并测试runFn在分配给的匿名函数内部被调用onSave

标签: angularunit-testingkarma-jasmine

解决方案


推荐阅读