Following is the sample unit test code for following methods


  • Out of all different ways to test controllers, one of the most recommended manner is to inject $rootScope and $controller
  • $scope variable is defined outside of different functions for it to be accessed across the functions
  • beforeEach function defines the module and inject $rootScope and $controller
Unit Tests Code Example for CompanyCtrl Controller
describe( "CompanyCtrl", function(){
	// Define the $scope variable that shall be accessed in different unit tests functions
	var scopeMock;
	// Define the module, helloApp before each unit tests start executing
	// Inject the $rootScope and $controller 
	// Read $rootScope on this page:$rootScope
	// Read about $controller on this page:$controller
					function( $rootScope, $controller ){		
						scopeMock = $rootScope.$new();		
						$controller( 'CompanyCtrl', {$scope: scopeMock} );
	// Tests the length of the default $scope.companies model object
	it( "should create model \"companies\" with 4 companies", function() {		
		expect( scopeMock.companies.length ).toBe( 4 );
	// Test the addRow behavior on the $scope object. 
	it( "should add an entry to the model \"companies\"", function() { = "Prokarma Technologies";
		scopeMock.employees = 2500;
		scopeMock.headoffice = "Hyderabad";
		expect( scopeMock.companies.length ).toBe( 5 );
		expect( ).toEqual( '' );
		expect( scopeMock.employees ).toEqual( '' );
		expect( scopeMock.headoffice ).toEqual( '' );
	// Test the removeRow behavior of the $scope object
	it( "should remove an entry from the model \"companies\"", function() {		
		var name = "Infosys Technologies";		
		scopeMock.removeRow( name );
		expect( scopeMock.companies.length ).toBe( 3 );


comments powered by Disqus