Angularjs和qunit测试

时间:2014-02-25 08:31:11

标签: angularjs unit-testing testing qunit

我有一个angularjs web应用程序,并希望使用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;
        }
    }

现在我想用valuesqunit函数编写单元测试。我将所有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/ $ injector / unpr?p0 = $ rootElementProvider%20%3C-%20 $ rootElement%20%3C-%20 $ location%20%3C-%20 $路线在:

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

如何正确注入控制器并使用$scope$rootScope$location以及其他服务?

谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个而不是你的控制器

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

答案 1 :(得分: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很有用。

可以轻松地向被测控制器注入更多。