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

expected scope variable undefined in karma test

我无法理解范围在业力测试中是如何初始化的。我希望在测试运行时预设一个范围变量,但它一直返回为未定义。

我错过了什么?

测试用例

    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: ''
            };
    }]);

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

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

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

    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('');
                });
            });
    });