我正在尝试为我的 Controller 创建单元测试。
我有类似的东西
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….
});
});
})
我被错误消息困住了,我不确定如何进行工厂测试。我不确定如何在 Controller 中为我的服务测试 getProduct
方法。
最佳答案
在单元测试中,您需要创建一个新的作用域对象,而不仅仅是一个空的对象字面量。并且在实例化 Controller 时还需要注入(inject)一个 testFactory 对象。在我的脑海中,像这样的事情:
describe('Test ', function () {
beforeEach(module('myApp'));
var $controller, testFactory, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function(_$controller_, _$rootScope_, _testFactory_){
$controller = _$controller_;
$rootScope = _$rootScope_;
testFactory = _testFactory_;
}));
scope = $rootScope.$new();
describe('Initial test', function() {
it('should return data', function() {
var controller = $controller('testCtrl', {$scope:scope, testFactory:testFactory});
// expect something here
});
});
})
关于javascript - 在我的案例中如何解决 'undefined is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29931725/