Testing angular controllers with Jasmine
Testing angular controllers with Jasmine
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.directive('formLogin', function () {
return {
restrict: 'E',
template: '<div><p ng-show="visible">Some content</p><button ng-click="showForm()">Show / hide</button><div>',
replace: true,
controller: function ($scope) {
$scope.visible = false;
$scope.showForm = function () {
$scope.visible = !$scope.visible
}
}
}
});
})(angular);
// ---SPECS-------------------------
describe('myApp', function () {
var scope
, element
;
beforeEach(function () {
module('myApp');
});
describe('Directive: formLogin', function () {
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<form-login></form-login>');
$compile(element)(scope);
}));
it('Visible initially has false value', function() {
expect(scope.visible).toBe(false);
});
it('Changes state of scope.visible', function() {
expect(scope.visible).toBe(false);
scope.showForm();
expect(scope.visible).toBe(true);
});
});
});
// --- 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);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();