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;
})();
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");
});
});
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");
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With