AngularJS, like unit test, to ensure that directives like ng-click point to valid code

I use Jasmine to write unit tests for our controllers, but I wanted to get community feedback on how to handle this situation ...

I have a controller - InvoiceController, for example:

angular.module('myModule').controller('myController', ['$scope', function($scope) { $scope.doSomething = function() { $scope.something = 'bar'; }; } ]}); 

In my unit tests, I verify that my controller has the expected methods:

 it('should be able to do some work', function() { // initialize scope properties scope.someProperty = 'foo'; // load controller using those properties injectController(); // do I have all of the functions necessary to do this work? expect(typeof (scope.doSomething)).toBe('function'); // now execute test scope.doSomething(); expect(scope.something).toBe('bar'); } 

And finally, in my html, I have an element with ng-click, for example:

 <button ng-click="doSomehing()">Do Something</button> 

It looks good, right? BUT, did anyone catch what I did wrong?

The ng-click method has a spelling error, but all tests are green and life seems ruddy ... until I try to click on this guy and nothing will happen. There is no rendering time error, when clicked there is no error. Hm.

Several times when I refactored code, it bothered me. I will rename doSomething to doSomethingCooler in the unit test and in the controller, but skip the place in html. After a minute of scratching my head, I see what was missed.

I would really like to make sure that the markup is valid. E2E tests seem like an obvious solution, but they tend to be fragile, so we hope there are some alternatives.

If it were ASP.Net, I would snap click events from the code behind to get compile-time errors and runtime errors.

Thoughts ??

Tad

+6
source share
1 answer

One thing you can do is get the template text and run $compile on it. And then snap it to the area of ​​your controller. Then you can do something like dom.find('[ng-click]').click(); which should be selected if any of them are not defined in the area of ​​your controller. This is similar to the way you usually check directives.

+2
source

Source: https://habr.com/ru/post/951834/


All Articles