Angularjs 和 qunit 测试

标签 angularjs unit-testing testing qunit

我有一个 angularjs 网络应用程序,想在其中使用 qunit 进行单元测试。我有一个 Controller :

    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/ $injector/unpr?p0=$rootElementProvider%20%3C-%20$rootElement%20%3C-%20$location%20%3C-%20$route at:

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

如何正确注入(inject)controller并使用$scope, $rootScope, $location 和其他服务?

谢谢。

最佳答案

试试这个而不是你的 Controller

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

关于Angularjs 和 qunit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22008531/

相关文章:

angularjs - 使用 element.AddClass 添加 Angular js 指令,该指令仅限于充当 'class'

javascript - 如何从 ui bootstrap 的 uibModal.open 设置组件输出绑定(bind)

javascript - 在 Ui.grid 中使用 rowTemplate 会禁用 angularjs 中的选择

ios - 如何创建在触发功能时通过的测试?

ios - 在 Xcode 单元测试中模拟网络连接? (可能与 AFNetworking 有关)

c# - 使用 EF6( Entity Framework 6)编写单元测试

android - 如何为 android 仪器测试设置环境并制作示例 Activity UI 测试?

testing - 在多模块项目中继承存储库

javascript - Angular 模态窗口(UI-路由器/指令)

ruby-on-rails - 使用 rspec 测试登录/注销(保留两个 API 调用之间的 session 数据)