Testing angular controllers with Jasmine
Testing angular controllers with Jasmine
by Krzysztof Safjanowski
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
(function (angular) {
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope, environment) {
$scope.testValue = 'test environment';
$scope.init = function () {
$scope.testValue = 'development environment';
};
environment.development && $scope.init();
});
myApp.factory('environment', function () {
return {
development: true
}
});
})(angular);
// ---SPECS-------------------------
describe('myApp', function () {
var scope,
controllerInstantiate,
mockEnvironment = {};
beforeEach(function () {
module('myApp');
});
beforeEach(function () {
module(function ($provide) {
$provide.value('environment', mockEnvironment);
});
});
describe('MyCtrl', function () {
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
controllerInstantiate = $controller;
}));
function createController() {
return controllerInstantiate('MyCtrl', {
'$scope': scope
});
}
it('prevents call .init() on test environment', function () {
mockEnvironment.development = false;
createController();
expect(scope.testValue).toBe('test environment');
});
it('calls init on development environment', function () {
mockEnvironment.development = true;
createController();
expect(scope.testValue).toBe('development environment');
});
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
...