【发布时间】: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