5

I have seen that in order to simulate user action on the DOM generated by a directive, there are two approaches, both trigering an event:

How to trigger ng-change in directive test in AngularJS

The first approach uses jquery and the second one a function called browserTrigger defined in angular-scenario.js. The second one is supposed to be better as jquery would have a bug on event triggering (which I believe, I am not arguing :) ).

Using the angular-scenario means e2e testing for me. but I have seen egghead video and he seems to do unit testing. How is this possible ?

I guess he just copied the function ?

I think I am going to test directives as e2e tests, it makes more sense as unit test is more fore pure functions.


Well, I just found that browserTrigger is something internal not supposed to be used directly : https://github.com/angular/angular.js/issues/5178


Thanks!

2
  • I've tried to use ngScenario before in order to test a directive and found it trickier to use than just triggering events manually. Perhaps I haven't tried hard enough. Anyway, I've got the tests working with jQuery. You can check them out here. Hopefully they can be useful to you. Commented Dec 9, 2013 at 16:34
  • possible duplicate of Unit test angular right-click directive Commented Dec 22, 2014 at 13:10

2 Answers 2

9

As of 1.3.15 you can use triggerHandler to trigger a event as shown below,

it('should click the element',function(){
    element.triggerHandler('click') ;
    expect($scope.clicked).toBe(true);
});
Sign up to request clarification or add additional context in comments.

3 Comments

It is also shown in at the same page for older versions
Is it possible to simulate a $scope.function() call?
I mean something like <div ng-click="doSomething()"></div>? For some reason I am absolutely unable to test this kind of behavior...
1

simple and it works, example, in unit test env:

spyOn(self, 'updateTransactionPrice');


var el = compile('<form name="form" latest novalidate json-schema="main.schema_discount" json-schema-model="main._data"><input type="text" ng-model="main._data.reverse_discount" ng-class="{ \'form-invalid\': form.reverse_discount.$invalid }" ng-change="main.transactionPrice(form);" name="reverse_discount" class="form-control-basic" placeholder="" ng-disabled="!main.selectedProduct.total_price"></form>')(scope);
el.find('input').triggerHandler('change');

expect(self.updateTransactionPrice).toHaveBeenCalled();

Comments

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.