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();
    });


  });
});
3
  • Did you look here? stackoverflow.com/questions/32565101/… Commented Sep 17, 2015 at 16:49
  • 1
    @DianaR I have tried to modified but still not work. Can you provide an example? Commented Sep 17, 2015 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? Commented Sep 17, 2015 at 18:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.