2014-02-25 148 views
2

我有一個angularjs web應用程序,並希望使用qunit進行單元測試。我有一個控制器:Angularjs和qunit測試

function RootCtrl($scope, $rootScope, $window, $location) { 
     // logger is empty at the start 
     $scope.logger = ''; 
     // we have no login error at the start 
     $scope.login_error = ''; 

     // 
     // Get values array of object 
     // 
     $rootScope.values = function (obj) { 
      var vals = []; 
      for(var key in obj) { 
       if(key !== '$$hashKey' && key !== 'checked') 
        vals.push(obj[key]); 
      } 
      return vals; 
     } 
    } 

現在我想編寫單元測試與qunitvalues功能。我將所有js文件包括到test/index.htmlqunit.css。現在我test.js有以下內容:

var injector = angular.injector(['ng', 'myApp']); 

var init = { 
    setup : function() { 
     this.$scope = injector.get('$rootScope').$new(); 
    } 
} 

module('RootCtrl', init); 

test('RootCtrl', function(){ 

    var $controller = injector.get('$controller'); 

    $controller('RootCtrl', { 
      $scope : this.$scope, 
     $location : this.$location 
    }); 

    equal(['value'], $controller.values({'key' : 'value'})) 

}); 

但我發現了錯誤:http://docs.angularjs.org/error/ $噴油器/ unpr P0 = $ rootElementProvider%20%3 C-%$ 20 rootElement的%20%3 C-%$ 20的位置% 20%3C-%$ 20路線在:

$controller('RootCtrl', { 
      $scope : this.$scope, 
     $location : this.$location 
    }); 

如何正確地注入控制器和使用$scope$rootScope$location和它的另一個服務?

謝謝。

回答

0

試試這個,而不是你的控制器

$controller('RootCtrl',['$scope', '$rootScope', '$location','$route', function ($scope, $rootScope, $location, $route) { 
      $scope : this.$scope, 
      $location : this.$location 
    }]); 
+0

新增,得到相同的錯誤 – 0xAX

0

也有類似的問題,所以在這裏,因爲沒有其他答案。

我最終使用:

客戶端代碼:

var myApp= angular.module('myApp', []); 

myApp.controller('myCtrl', function ($scope) { 
    //angular client side code 

    $scope.canSubmit = function() { 
     //some logic 
     return true; 
    } 
} 

Qunit測試:

var ctrl, ctrlScope, injector; 

module("Testing the controller", { 
    setup: function() { 
     angular.module('myApp'); 
     injector = angular.injector(['ng', 'myApp']); 

     ctrlScope = injector.get('$rootScope').$new(); 
     ctrl = injector.get('$controller')('myCtrl', { $scope: ctrlScope }); 

     ctrlScope.model = { 
      //model object 
     }; 
    }, 
    teardown: function() { 

    } 
}); 

test("Given something happened then allow submit", function() { 
    ok(ctrlScope.someFunction(...), "some functionality happened"); 
    equal(true, ctrlScope.canSubmit()); 
}); 

This blog post是有益的。

人們可以很容易地注入更多的被測試的控制器。