24

我正在使用 jasmine 进行 angularJS 测试。在我看来,我使用的是“Controller as”语法:

<div ng-controller="configCtrl as config">
    <div> {{ config.status }} </div>
</div>

如何在茉莉花中使用这些“范围”变量?“控制器为”指的是什么?我的测试如下所示:

describe('ConfigCtrl', function(){
    var scope;

    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(function($rootScope){
        scope = $rootScope.$new();

        $controller('configCtrl', {$scope: scope});
    }));

    it('should have text = "any"', function(){
        expect(scope.status).toBe("any");
    });
}); 

调用scope.status肯定会以错误结束:

Expected undefined to be "any".

更新:控制器(从 TypeScript 编译的 javascript)看起来像这样:

var ConfigCtrl = (function () {
    function ConfigCtrl($scope) {
        this.status = "any";
    }
    ConfigCtrl.$inject = ['$scope'];
    return ConfigCtrl;
})();
4

2 回答 2

47

解决方案是在测试中实例化控制器时使用“controller as”语法。具体来说:

$controller(' configCtrl as config ', {$scope:scope});

期望(范围.config.status).toBe(“任何”);

现在应该通过以下内容:

describe('ConfigCtrl', function(){
    var scope;

    beforeEach(angular.mock.module('busybee'));
    beforeEach(angular.mock.inject(function($controller,$rootScope){
        scope = $rootScope.$new();

        $controller('configCtrl as config', {$scope: scope});
    }));

    it('should have text = "any"', function(){
        expect(scope.config.status).toBe("any");
    });
}); 
于 2013-10-25T23:29:10.210 回答
15

当我们使用controller as语法时,应该不需要将 $rootScope 注入我们的测试。以下应该可以正常工作。

describe('ConfigCtrl', function(){
    beforeEach(module('busybee'));

    var ctrl;

    beforeEach(inject(function($controller){
        ctrl = $controller('ConfigCtrl');
    }));

    it('should have text = "any"', function(){
         expect(ctrl.status).toBe("any");
    });
});
于 2015-02-23T11:17:52.627 回答