如何在Jasmine中使用带有“Controller as”语法的范围变量?

时间:2013-08-27 19:08:17

标签: angularjs 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;
})();

2 个答案:

答案 0 :(得分:46)

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

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

期望(的 scope.config.status )砥( “任何”);

以下内容现在应该通过:

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");
    });
}); 

答案 1 :(得分: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");
    });
});