unit testing angularjs directive

后端 未结 1 1106
北海茫月
北海茫月 2021-02-09 04:50

I would like to start doing unit testing for my angularjs project. That\'s far from being straight forward, I find it really difficult. I\'m using Karma and Jasmine. For testing

相关标签:
1条回答
  • 2021-02-09 05:53

    Here is the way to go https://github.com/vojtajina/ng-directive-testing

    Basically, you use beforeEach to create, compile and expose an element and it's scope, then you simulate scope changes and event handlers and see if the code reacts and update elements and scope appropriately. Here is a pretty simple example.

    Assume this:

    scope: {
      myPerson: '='
    },
    link: function(scope, element, attr) {
      element.bind('click', function() {console.log('testes');
        scope.$apply('myPerson = "clicked"');
      });
    }        
    

    We expect that when user clicks the element with the directive, myPerson property becomes clicked. This is the behavior we need to test. So we expose the compiled directive (bound to an element) to all specs:

    var elm, $scope;
    
    beforeEach(module('myModule'));
    
    beforeEach(inject(function($rootScope, $compile) {
      $scope = $rootScope.$new();
      elm = angular.element('<div t my-person="outsideModel"></div>');
      $compile(elm)($scope);
    }));
    

    Then you just assert that:

    it('should say hallo to the World', function() {
      expect($scope.outsideModel).toBeUndefined(); // scope starts undefined
      elm.click(); // but on click
      expect($scope.outsideModel).toBe('clicked'); // it become clicked
    });
    

    Plnker here. You need jQuery to this test, to simulate click().

    0 讨论(0)
提交回复
热议问题