testing angularjs directive with jasmine
by bullrout
HTML
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="https://jasmine.github.io/2.0/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.0/lib/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
(function (angular) {
// Create module
var elemstyle = angular.module('elemstyle', []);
// Controller which set the max height that triggers
// style - class switch
elemstyle.controller('HeightBasedElCtrl', ['$scope', function($scope){
$scope.data = {
maxH : 50
};
}]);
// Directive : changes the class of element - bg color
elemstyle.directive('heightBasedCss', [function(){
return {
replace : true,
transclude : true,
template : '<div ng-class="{true : \'small-container\', false: \'big-container\'} [ checkHeight() ]" ng-transclude><div>',
link: function(scope, elem, attrs) {
elem.css({ 'width' : '100px' });
scope.checkHeight = function() {
return elem[0].offsetHeight < scope.data.maxH;
};
}
};
}]);
})(angular);
//------- SPECS - TESTING -------------
describe('elemstyle', function () {
var scope,
controller,
element,
directive;
beforeEach(function () {
module('elemstyle');
element = angular.element(
'<div height-based-css>' +
'<div ng-bind="data.content"></div>' +
'</div>'
);
inject(function (_$rootScope_, _$compile_, _$controller_, _$document_) {
scope = _$rootScope_.$new();
$controller = _$controller_('HeightBasedElCtrl', {
'$scope': scope
});
_$compile_(element)(scope);
scope.$digest();
$document = _$document_;
});
});
//-- test controller
describe('Controller', function () {
it('sets the max height', function () {
expect(scope.data.maxH).toBe(50);
});
});
//-- test directive
describe('Directive', function () {
...