Unit testing of the AngularJS directive that uses the scroll function

I have a directive that listens for a scroll event and then adds a class (so that it snaps to the top).

My question is, how can I test this behavior? Should I make fun of $ window, or is there a better way to do this? I could study the script test, but it seems too difficult to check out a small directive.

The directive looks like this:

directiveModule.directive('whenFilterScroll',function($window){ return function(scope, element, attr){ var logoHeight = 110; angular.element($window).bind('scroll', function(){ if(this.pageYOffset > logoHeight && element.css('position') != 'fixed') { element.addClass('filtersFixed'); } if(this.pageYOffset < logoHeight && element.css('position') == 'fixed') { element.removeClass('filtersFixed'); } }); } }); 
+4
source share
1 answer

Option # 1: mock $ window object

Yes, you would mock $ window. This is not too much for a small directive, because your directive is based on it and only on this. From what you say, if you do not test it with mocks, you do not test it at all, and then how can you be sure that your directive works?

No matter how small the file or class or method is, it should always be backed up by a test.

Option number 2: do not miss $ window, split your code into smaller verifiable functions

If you do not want to use the layout, you can rewrite your code so that it takes each step in parts and allows you to supply variables, for example:

 var shouldAddFilterClass = function (pageYOffset, logoHeight, cssPosition) { return pageYOffset > logoHeight && cssPosition != 'fixed'; }; var shouldRemoveFilterClass = function (pageYOffset, logoHeight, cssPosition) { return pageYOffset < logoHeight && cssPosition == 'fixed'; }; /* ...rest of code... */ angular.element($window).bind('scroll', function () { if (shouldAddFilterClass(this.pageYOffset, logoHeight, element.css('position'))) { element.addClass('filtersFixed'); } if (shouldRemoveFilterClass(this.pageYOffset, logoHeight, element.css('position'))) { element.removeClass('filtersFixed'); } }); 

Then in your tests you can do this:

 assert(shouldAddFilterClass(100, 50, 'static') === true); assert(shouldRemoveFilterClass(100, 50, 'static') === false); assert(shouldAddFilterClass(100, 200, 'fixed') === false); assert(shouldRemoveFilterClass(100, 200, 'fixed') === true); 

This way you check the conditions that are checked by the callback. You can then check to make sure the element has the correct CSS classes. All this without ridicule $ window.

0
source

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


All Articles