Created
April 30, 2014 02:45
-
-
Save AlphaGit/57cf51d23e246bd01226 to your computer and use it in GitHub Desktop.
Decoupled controller for unit testing without depending on $scope too much
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('Testable controller', function() { | |
beforeEach(module('MyApp')); | |
it('should be testable against the controller logic', inject(function($controller, $rootScope, ApiService) { | |
var $scope = $rootScope.new(); | |
var controller = $controller('MyController', { $scope: $scope, ApiService: ApiService }); | |
expect(controller.generateGreeting).toBeDefined(); | |
var greeting = controller.generateGreeting(); | |
expect(greeting).toBe('...'); | |
})); | |
it('should be testable against the scope bindings', inject(function($controller, $rootScope, ApiService) { | |
var $scope = $rootScope.new(); | |
var controller = $controller('MyController', { $scope: $scope, ApiService: ApiService }); | |
expect($scope.name).toBe("world"); | |
$scope.getGreeting(); | |
expect($scope.messageToBeDisplayed).toBe('...'); | |
})); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MyController = function($scope, ApiService) { | |
var ctrl = this; // reference to controller | |
// controller "private" parts | |
var defaultGreeting = "Hello"; | |
// controller "public" logic | |
this.generateGreeting = function() { | |
var apiGreeting = ApiService.getDefaultGreeting(); | |
var prefix = apiGreeting || defaultGreeting; | |
return prefix + ' ' + $scope.name; | |
}; | |
// bindings to $scope | |
$scope.name = "world"; // default name, bound for the user to input | |
$scope.messageToBeDisplayed = null; | |
$scope.getGreeting = function() { // bound to a button or a ng-change directive | |
$scope.messageToBeDisplayed = ctrl.generateGreeting(); | |
}; | |
}; | |
angular.module('MyApp').controller('MyController', MyController); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment