我有一个简单的待办事项应用程序的控制器,它做两件事,(1)查询数据库,(2)将新功能发布到数据库中。控制器运行正常,但我现在正在尝试实施茉莉花测试,而且我无法正确设置测试。我想测试一个新项目是否已创建并保存到数据库中,但在我甚至可以达到该部分之前,我的测试因为未定义的变量而失败,并且控制器似乎无法从DB获取任何东西 - 它总是返回一个空数组。这是我的考试:
describe('TodoListController', function() {
beforeEach(module('TodoApp'));
var $controller;
var $scope;
var Dates;
beforeEach(inject(function($rootScope, _Dates_, _$controller_) {
$scope = $rootScope.$new();
Dates = _Dates_;
$controller = _$controller_;
}));
describe('$scope.postTodo', function() {
it('creates a new todo item', function() {
var controller = $controller('TodoListController', { $scope: $scope });
var item = {
date: "2015-02-17",
day: "Tuesday",
new_todo: "Make breakfast for everyone"
}
// testDateList = Dates.query({related:'True'});
// console.log(testDateList); This returns an empty array
// $scope.postTodo(item); Test fails because "theDate" is undefined
});
});
});
这是相应的控制器
app.controller('TodoListController', function($scope, Todos, Dates) {
$scope.dateList = Dates.query({related:'True'});
$scope.postTodo = function(item) {
if(item) {
var theDate = _.findWhere($scope.dateList, {date: item.date});
var todo_item = {
todo: item.new_todo,
position: 0,
date: theDate.id
}
var newTodo = new Todos(todo_item);
newTodo.$save().then(function(result) {
console.log(result);
}).then(function() {
// Update your view....
// console.log('success');
theDate.todos.push(newTodo);
theDate.new_todo = null;
}, function(failure) {
console.log('failure', failure);
// Bring up a notice
});
}
};
});
修改
我在运行测试时开始使用控制器代码的一部分,我认为这与Dates查询未运行有关。我不正确地将其注入测试中吗?