How do I check a directive in the link phase?

Here is some Javascript that calls jqLite call trigger

inside link

AngularJS directive function .

angular.
  module('myApp').
  directive('myDirective',
    function($timeout) {
      return {
        link: function(scope) {

          scope.resetChosenElements = function() {
            $timeout(function() { 
                $('[chosen]').trigger('chosen:updated'); 
            }, 0);
          }

          scope.resetChosenElements();          

        }
      };
    }
  );

      

How can I write a test that checks what trigger

is called when a directive is created without spying on $.trigger

? (I don't want to follow $.trigger

, because this catches all calls made to it, including other directives).

Is there a way to keep track of the argument element

that can be passed to link

?

EDIT: My comment on spying on element

seems to be causing confusion. I only meant that if the solution required adding element

to the arguments passed to link

then that would be fine. However, I am not currently using it otherwise, so it is excluded from the argument list.

+3


source to share


1 answer


Annoy that the function is being mocked trigger

, you can track the event function element

as @Michael Benford says that you are not using element

in your code for example seems confusing given your question in any way:

This example uses ChaiJS as the validation tool and SinonJS as the spies / stubs / mocks library. You must add spy

toelement

customEvent



beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
    $scope = $rootScope.$new();
    compile = $compile;
    $httpBackend = _$httpBackend_;
    el = angular.element('<elementTemplateTag></elementTemplateTag>');
    compile(elm)($scope);
    spy = sinon.spy(el, "customEvent"); // Add spy on the event call
}));

afterEach(function(){
 el.customEvent.restore(); //clean spy calls
});

it('element.customEvent() called once', function() {

    el.trigger('customEvent');
    $timeout.flush(); // release all timeouts

    expect(el.customEvent.calledOnce()).to.be.true;
});

      

I hope this works for you.

+1


source







All Articles