我正在尝试为我的控制器创建单元测试。
我有类似
的东西angular.module('myApp').controller('testCtrl', ['$scope', 'testFactory',
function($scope, testFactory) {
//I am getting the error when I ran Karma
//TypeError: 'undefined' is not a function (evaluating
//'$scope.$watch')
$scope.$watch(function(){
return testFactory.returnItem; // watch the factory returned data
}, function(newVal){
console.log('call here')
});
}
]}
在我的工厂文件
中angular.module('myApp').factory('testFactory', ['Product','$cookies','$q',
function(Product ,$cookies, $q) {
var service = {};
service.getProduct = function() {
var deferred = $q.defer();
var that = this;
Product.query({
Id: 123,
}, function(product) {
that.returnItem = product;
deferred.resolve(product);
});
return deferred.promise;
};
return service;
}
]);
我的单元测试
describe('Test ', function () {
beforeEach(module('myApp'));
var $controller, testFactory;
// Initialize the controller and a mock scope
beforeEach(inject(function(_$controller_, _testFactory_){
$controller = _$controller_;
testFactory = _testFactory_;
}));
describe('Initial test', function() {
it('should return data', function() {
var $scope = {};
var controlelr = $controller('testCtrl', {$scope:$scope});
//not sure what to do next….
});
});
})
我遇到了错误消息,我不知道该怎么做工厂测试。我不确定如何在控制器中测试我的服务的getProduct
方法。
答案 0 :(得分:7)
在单元测试中,您需要创建一个新的范围对象,而不仅仅是一个空的对象文字。并且还需要在实例化控制器时注入testFactory对象。在我的头顶,这样的事情:
XMLObject
答案 1 :(得分:1)
您在倒数第二行缺少} 。正确的将是
angular.module('myApp').controller('testCtrl', ['$scope', 'testFactory',
function($scope, testFactory) {
//I am getting the error when I ran Karma
//TypeError: 'undefined' is not a function (evaluating
//'$scope.$watch')
$scope.$watch(function(){
return testFactory.returnItem; // watch the factory returned data
}, function(newVal){
console.log('call here')
});
}
]}