【问题标题】:Jasmine check if private method has been calledJasmine 检查是否调用了私有方法
【发布时间】:2019-06-06 16:45:52
【问题描述】:

我有一个公开方法的 Angular 服务。在它的主体内部,可以根据条件调用两个不同的私有方法。

我如何用 jasmine 根据传递给公共方法的输入参数检查是否调用了一个或另一个方法? 我知道我们不应该测试私有方法,但是确实在这里我只是想验证公共是否调用了正确的私有方法。我不想公开私有方法,因为我只想要服务提供的一个访问点。

我的服务方式:

public  addOrUpdateShoppingList(list: ShoppingList) {
  if (!list) {
    return Promise.reject("List object is null!");
  }

  if (!list.id) { 
    return this.createNewList(list);
  }

  return this.updatelist(list);
}

private createNewList(list: ShoppingList) {
  const id = this.db.createId();
  list.id = id;
  return this.db.collection<ShoppingList>(this.SHOPPING_LIST_COLLECTION)
                .doc(id)
                .set(list);
}

private updatelist(list: ShoppingList) {
  return this.db.collection<ShoppingList>(this.SHOPPING_LIST_COLLECTION)
                .doc(list.id)
                .update(list);

}

茉莉花测试:

it("addOrUpdateShoppingList should invoke createNewList() if the list doesn't have id.", () => {
const service: DataService = TestBed.get(DataService);
const mockedList: ShoppingList[] = [
  {
    id: null,
    isActive: true,
  }
 ];

service.addOrUpdateShoppingList(newList);

// I tried even with this "workaround", but it fails, even if the private method is accessed
const sp = spyOn<any>(service, "createNewList").and.callThrough();
expect(sp).toHaveBeenCalled();

});

【问题讨论】:

    标签: angular unit-testing karma-jasmine


    【解决方案1】:

    您不能直接测试私有方法 - 毕竟这是私有方法的要点:在定义它们的类之外无法看到它们。有关一些解决方法,请参阅this Stack Overflow question

    但是,在您的情况下,您很幸运。您的两个私有方法都会调用数据库服务。只需监视该服务调用并测试传递的内容 - 您是尝试 set 还是 update - 这将确定调用了哪个内部私有方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      相关资源
      最近更新 更多