因果报应测试中未定义的预期范围变量

expected scope variable undefined in karma test

本文关键字:范围 变量 测试 未定义 因果报应      更新时间:2023-10-14

我很难理解因果报应测试中作用域是如何初始化的。我希望在测试运行时预先设置一个范围变量,但它总是以未定义的形式返回。

我错过了什么?

测试用例

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

我重构了测试代码,现在它可以工作了:

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

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

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