How to use scope variables with the “Controller as” syntax in Jasmine?

荒凉一梦 提交于 2019-12-05 09:10:09

问题


I'm using jasmine for angularJS testing. In my views, I'm using the "Controller as" syntax:

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

How can I use these "scope" variables in jasmine? What does the "Controller as" refer to? My test looks like following:

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

Calling scope.status ends, for sure, with the error:

Expected undefined to be "any".

UPDATE: Controller (compiled javascript from TypeScript) looks like this:

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

回答1:


The solution is to use the "controller as" syntax when instantiating your controller in your test. Specifically:

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

expect(scope.config.status).toBe("any");

The following should now pass:

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



回答2:


When we are using the controller as syntax, there should be no need to inject $rootScope into our test. The following should work just fine.

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


来源:https://stackoverflow.com/questions/18473574/how-to-use-scope-variables-with-the-controller-as-syntax-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!