预期范围变量在业力测试中未定义

时间:2015-02-13 14:10:39

标签: javascript angularjs unit-testing karma-runner

我无法理解在业力测试中如何初始化范围。我希望在测试运行时预设一个范围变量,但它会不确定地返回。

我错过了什么?

测试用例

    describe('loginController', function() {
        beforeEach(module('app'));

        var $controller, $scope;

        beforeEach(inject(function(_$controller_, $rootScope){
            $controller = _$controller_;
            $scope = $rootScope.$new();
        }));

        describe('$scope.login', function() {
            beforeEach(function() {
                controller = $controller('loginController', { $scope: $scope });
            });

            it('checks it initialized', function() {
                expect($scope.foo).toEqual('foo');
                expect($scope.bar).toEqual('bar');
                //expect($scope).toBeDefined();
                //expect($scope.loginData.userName).toEqual('');
                //expect($scope.loginData.password).toEqual('');
            });

控制器:

    angular.module('app').controller('loginController', ['$location', 
    'authService', function($scope, $location, authService) {

            $scope.foo = 'foo';
            $scope.bar = 'bar';

            $scope.loginData = {
                    userName: '',
                    password: ''
            };
    }]);

2 个答案:

答案 0 :(得分:5)

我重构了测试代码,现在可行了:

    describe('loginController', function() {
        beforeEach(module('app'));
        var controller, scope;

        beforeEach(inject(function($controller, $rootScope){
                scope = $rootScope.$new();
                console.log('scope1', scope);
                controller = $controller('loginController', {
                    $scope: scope
                });
            }));

            describe('login', function() {
                it('sets variables ', function() {
                    expect(scope).toBeDefined();
                    expect(scope.loginData).toBeDefined();
                    expect(scope.loginData.userName).toEqual('');
                    expect(scope.loginData.password).toEqual('');
                });
            });
    });

答案 1 :(得分:0)

尝试将$ controller注入您实例化控制器的函数:

            beforeEach(inject(function($controller) {
                controller = $controller('loginController', { $scope: $scope });
            }));