Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
})();
like image 410
pichsenmeister Avatar asked Aug 27 '13 19:08

pichsenmeister


2 Answers

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");
    });
}); 
like image 190
Beyers Avatar answered Nov 13 '22 02:11

Beyers


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");
    });
});
like image 32
andy_roddam Avatar answered Nov 13 '22 01:11

andy_roddam