我有一个使用 angularjs 服务承诺的控制器。我已经针对控制器编写了 jasmine 单元测试,因此控制器功能如下所示:
this.getTodos = function () {
TodoService.getTodos().then(function (todos) {
$scope.Todos = todos;
},
function (error) {
// TODO: display the error pop up
console.log(error);
});
};
看起来这不适用于视图?如果我将函数更改为:
TodoService.getTodos().then(function (todos) {
$scope.Todos = todos;
},
function (error) {
// TODO: display the error pop up
console.log(error);
});
然后它可以工作,但是我无法测试我的控制器功能。我的首选方式是将其用作 this.getTodos、this.saveTodo、this.DeleteTodo 等......
请问有什么建议吗?
非常感谢
====>> 更新
如前所述,测试都在工作,但视图不显示数据;似乎控制器 this.getTodos 根本没有被调用。....我不确定如何强制角度视图使用控制器 getTodos ...测试如下:
以下茉莉花测试工作正常:
it("Reading todos...", inject(function ($q) {
var deferredRead = $q.defer();
spyOn(todoServiceMock, "getTodos").and.returnValue(deferredRead.promise);
deferredRead.resolve([{ TodoId: 10, Description: "Test", Completed: false },
{ TodoId: 11, Description: "Test", Completed: false }]);
todoController.getTodos();
scope.$apply();
expect(scope.Todos.length).toBe(2);
}));
it("Reading todos, error...", inject(function ($q) {
var deferredRead = $q.defer();
spyOn(todoServiceMock, "getTodos").and.returnValue(deferredRead.promise);
deferredRead.reject("There are no todos available!");
todoController.getTodos();
scope.$apply();
expect(scope.Todos.length).toBe([]);
}));
但是,视图不会填充行...
该视图的代码如下:
<tr class="animate" ng-repeat="Todo in Todos | orderBy:'TodoId' | filter: filterTodo">
<td class="col-sm-1">{{Todo.TodoId}}</td>
<td class="col-sm-3">{{Todo.Description}}</td>
<td class="col-sm-1">
<span class="glyphicon glyphicon-check" ng-show=" {{Todo.Completed}}==true"></span>
<span class="glyphicon glyphicon-unchecked" ng-show="{{Todo.Completed}}==false"></span>
</td>
<td class="col-sm-2">
<a href="" ng-click="selectTodo(Todo)"><span class="glyphicon glyphicon-edit"></span></a>
</td>
</tr>