Unit testing Angular JS controllers that use "Controller as" syntax
Most of the Angular unit testing examples are based around using $scope in the controller, but using the "Controller as" syntax is also becoming popular. In this case a slight modification is needed in the test setup.
Given a controller setup such as:
The test setup needs to be something like this:
Seems to work ok for me - let me know if there is a better way!
Given a controller setup such as:
<div ng-controller="ProjectsCtrl as projects">
{{ projects.total }}
</div>
The test setup needs to be something like this:
describe('ProjectCtrl', function() {
beforeEach(angular.mock.module('app'));
beforeEach(function() {
inject(function($controller, $rootScope) {
scope = $rootScope.$new();
//here is where we add in "Controller as" detail
ProjectsCtrl = $controller('ProjectsCtrl as projects', {
$scope: scope
});
});
});
it('should have project total defined ', function() {
expect(scope.projects.total).toBeDefined();
});
});
Seems to work ok for me - let me know if there is a better way!
Comments
Post a Comment