vendredi 29 mai 2015

How to properly unit test directives with DOM manipulation?

Before asking my real question, I have a different one... Does it make sense to unit test DOM manipulation in Angular directives?

For instance, here's my complete linking function:

function linkFn(scope, element) {
    var ribbon = element[0];
    var nav = ribbon.children[0];

    scope.ctrl.ribbonItemClick = function (index) {
        var itemOffsetLeft;
        var itemOffsetRight;
        var item;

        if (scope.ctrl.model.selectedIndex === index) {
            return;
        }

        scope.ctrl.model.selectedIndex = index;

        item = nav.querySelectorAll('.item')[index];

        itemOffsetLeft = item.offsetLeft - ribbon.offsetLeft;
        itemOffsetRight = itemOffsetLeft + item.clientWidth;

        if (itemOffsetLeft < nav.scrollLeft) {
            nav.scrollLeft = itemOffsetLeft - MAGIC_PADDING;
        }

        if(itemOffsetRight > nav.clientWidth + nav.scrollLeft) {
            nav.scrollLeft = itemOffsetRight - nav.clientWidth + MAGIC_PADDING;
        }

        this.itemClick({
            item: scope.ctrl.model.items[index],
            index: index
        });

        $location.path(scope.ctrl.model.items[index].href);
    };

    $timeout(function $timeout() {
        var item = nav.querySelector('.item.selected');
        nav.scrollLeft = item.offsetLeft - ribbon.offsetLeft - MAGIC_PADDING;
    });
}

This is for a scrollable tabbed component and I have no idea how to test the 3 instances of nav.scrollLeft = x.

The first two if statements happen when an item - which is only partially visible - is clicked. The left/right (each if) item will be snapped to the left/right border of the component.

The third one, is to place the selected item in view if it's not visible when the component is loaded.

How do I unit test this with Karma/Jasmine. does it even make sense to do it or should I do functional tests with Protractor instead?

Aucun commentaire:

Enregistrer un commentaire