0

I am doing an AngularJS unit test and use Karma - Coverage to see the result. Here is my code.

todomvc.directive('todoBlur', function () {
  return function (scope, elem, attrs) {
    elem.bind('blur', function () {
        scope.$apply(attrs.todoBlur);
    });

    scope.$on('$destroy', function () {
        elem.unbind('blur');
    });
  };
});

I have written the following test case.

describe('TodoBlur', function() {
  var $compile,
    $rootScope;
  beforeEach(module('todomvc'));
  beforeEach(inject(function(_$compile_, _$rootScope_){
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));


  it('T', function() {
    var element = $compile("<todoBlur></todoBlur>")($rootScope);
    $rootScope.$digest();
    element.blur();
    var e = $.Event('keydown');
    e.which = 27;
    $rootScope.trigger(e);
    element.triggerHandler('keydown', 27);
    element.triggerHandler('keydown', 28);
  });
});

As you see, I tried many codes to try to test the keydown but none of them work. The result in Code coverage report remains unchanged. How can I test it? I am new to AngularJS and its unit test and I google and still cannot find any solutions.

Edit: I tried Unit testing Angular directive click handler and modified my code. But it still not work.

beforeEach(module('todomvc'));
describe('myCtrl', function () {

  var $scope, $rootScope;

  beforeEach(inject(function ($controller, _$rootScope_) {
    $scope = $rootScope.$new();
    $controller('myCtrl', { $scope: $scope });
    $rootScope = _$rootScope_;
  }));

  describe('T', function () {

    var element;

    beforeEach(function () {
        element = angular.element('<todoBlur/>');
        $compile(element)(scope);
        $scope.$digest();
    });


  });
});
Community
  • 1
  • 1
Joshua
  • 5,901
  • 2
  • 32
  • 52
  • Did you look here? http://stackoverflow.com/questions/32565101/unit-testing-angular-directive-click-handler/32565814#32565814 – Diana R Sep 17 '15 at 16:49
  • 1
    @DianaR I have tried to modified but still not work. Can you provide an example? – Joshua Sep 17 '15 at 17:17
  • what exactly the directive should do? I mean there are standard angularjs directives for blur and focus, why you need a custom directive? – Diana R Sep 17 '15 at 18:13

0 Answers0