2015-04-28 22 views
4

Я пытаюсь создать модульный тест для своего контроллера.Как решить «undefind не является функцией» в моем случае

У меня есть что-то вроде

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 для моего обслуживания в контроллере. Может ли кто-нибудь мне помочь? Большое спасибо!

ответ

7

В модульном тесте вам необходимо создать новый объект области видимости, а не только пустой литерал объекта. И вам также необходимо ввести объект 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 
     }); 
    }); 
}) 
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') 
     }); 
    } 
]} 
+0

спасибо, Это был хороший улов, но это была просто опечатка, и я все еще получаю ошибку. +1 – BonJon