Felix
Felix

Reputation: 245

best way to write Jasmine Test for DOM directive

I am a newbie to Jasmine BDD test for Angular JS - Can any one tell me a simple test case for this

My Directive

var app = angular.module('gls', []);

app.directive('changeBg', function() {
    return {
        restrict: 'A',
        link: function($scope, element, attrs) {
         element.bind('click', function(){
             element.css('background','red');
         });
        }
    };
});

Markup

<body ng-app="gls">
<a href='#' change-bg>Test link 1</a>
</body>

Upvotes: 0

Views: 407

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 27012

In general to test a directive, you need to create a scope, compile a simple template using the directive, and then perform some action it. In this case, the action is a click (which requires jQuery, as far as I know).

describe('Testing the changeBg directive', function() {
  var element = null;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope,$compile) {
    var scope = $rootScope.$new();
    var template = '<span change-bg></span>';
    element = $compile(template)(scope);
    element.click(); // Requires jQuery
  }));

  it('should be red after a click', function() {
    expect(element.css('background')).toEqual('red');
  });
});

You can see it in action in this plunkr.

Upvotes: 1

Related Questions