Last active
December 21, 2015 15:29
-
-
Save vtanathip/6327166 to your computer and use it in GitHub Desktop.
Example AngularJS Controller Unit Testing ( Mock all Services dependencies )
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
'use strict'; | |
angular.module('angularApp') | |
.controller('MainCtrl', function ($scope, $rootScope, loadConfig) { | |
//services dependecies ( should be mock ) | |
$scope.loadConfig = loadConfig.getConfig('main', $rootScope.lang); | |
//function change route | |
$scope.createRoute = function(link) { | |
$location.path(link); | |
}; | |
//switch language | |
$scope.switchLang = function() { | |
$rootScope.lang = ($rootScope.lang === 'th') ? 'en' : 'th'; | |
}; | |
}); |
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
'use strict'; | |
describe('Controller: MainCtrl', function () { | |
var MainCtrl,scope; | |
var mockService = { | |
getConfig: function () { | |
return {config: 'configX'}; | |
} | |
}; | |
// load the controller's module | |
beforeEach(function () { | |
module('angularApp'); | |
}); | |
// Initialize the controller and a mock scope | |
beforeEach(inject(function ($controller, $rootScope) { | |
MainCtrl = $controller; | |
scope = $rootScope.$new(); | |
MainCtrl = MainCtrl('MainCtrl', { | |
$scope: scope, | |
loadConfig: mockService | |
}); | |
})); | |
it('should not to be null and have configX', function () { | |
//should not be null because mockServices | |
expect(scope.loadConfig).not.toBe(null); | |
//should hava data | |
expect(scope.loadConfig.config).toBe('configX'); | |
}); | |
it('should change language from th to en', function(){ | |
//trigger to chage lang | |
scope.switchLang(); | |
//expect new lang to be en | |
expect(scope.lang).toBe('en'); | |
//trigger to change lang | |
scope.switchLang(); | |
//expect new lang to be th | |
expect(scope.lang).toBe('th'); | |
}); | |
it('should create workflow id',function(){ | |
//trigger to route page | |
scope.createRoute("/something"); | |
//expect new route path | |
expect(location.path()).toBe('/something'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment