jasmine + angular ex 8
test a directive
by ronapelbaum
HTML
<script src="https://jasmine.github.io/2.4/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.4/lib/jasmine-html.js"></script>
<script src="https://jasmine.github.io/2.4/lib/boot.js"></script>
<link rel="stylesheet" href="https://jasmine.github.io/2.4/lib/jasmine.css">
<script src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="https://code.angularjs.org/1.4.9/angular-mocks.js"></script>
JavaScript
//--------------BL------------
(function(angular) {
function greetDirective() {
function getGreeting(name) {
switch (name) {
case 'Bob':
return 'I hate you Bob!';
default:
return 'Hello ' + name;
}
}
return {
restrict: 'E',
template: '<div>{{greeting}}</div>',
scope: {
who: '='
},
link: function(scope, element, attrs) {
scope.greeting = getGreeting(scope.who);
}
};
}
angular.module('utils', []).directive('greet', greetDirective);
})(angular);
//--------------specs------------
describe('greet directive spec', function() {
var element, scope;
beforeEach(module('utils'));
beforeEach(inject(function($compile, $rootScope) {
//create scope
scope = $rootScope.$new();
//create element
element = angular.element('<greet who="data"></greet>');
// Compile the element with the scope
$compile(element)(scope);
}));
it('element should have "div" tag with text: "Hello Alice"', function() {
scope.data = 'Alice';
scope.$digest();
expect(element.find('div').html()).toEqual('Hello Alice');
});
it('element should have "div" tag with text: "I hate you Bob"', function() {
scope.data = 'Bob';
scope.$digest();
expect(element.find('div').html()).toEqual('I hate you Bob!');
});
});