Florian F
Florian F

Reputation: 8875

Unit test directive inside a directive

I'm having troubles unit testing a directive that wraps the ng-grid component.

I've written this punkler that shows the issue : http://plnkr.co/edit/HlB8Bt9M2TzsyM6XaDso?p=preview

There is a lot of code I know, but I can't reduce it more than that.

Basically, there is a custom-grid directive that wrapps the ng-grid component from angular-ui. I've made this directive because I have lots of grids in my app and I wouldn't duplicate the configuration of the grid.

The grid displayed on top of the test results use this directive. So , you can see it works fine :)

However, there is probably something I miss about how to test this directive. I've written a simple test that assert that the first row, first col displays 'Martoni' but it fails. The same test using the ng-grid directive pass.

Any idea what's wrong in my test code ?

Upvotes: 3

Views: 1497

Answers (1)

Jesus is Lord
Jesus is Lord

Reputation: 15409

http://plnkr.co/edit/WwTyuQXNklL7CnjOxsB2?p=preview

I've had issues before calling directives recursively (or at least nested-ly), particularly when they make use of the $compile service (and ng-repeat's, especially). I'm convinced there's a bug there but I haven't taken the time to find an isolated case. Anyway I think what you've found is some sort of bug, but there's an easy workaround.

If you look at the source for ngGrid you'll see that columns are only added if the width is big enough. When I stepped through in your second example w was negative, which led to addCol never being called.

var w = col.width + colwidths;
if (col.pinned) {
    addCol(col);
    var newLeft = i > 0 ? (scrollLeft + totalLeft) : scrollLeft;
    domUtilityService.setColLeft(col, newLeft, self);
    totalLeft += col.width;
} else {
    if (w >= scrollLeft) {
        if (colwidths <= scrollLeft + self.rootDim.outerWidth) {
            addCol(col);
        }
    }
}
colwidths += col.width;

This led me to believe that your elements had 0 height/width, which could be because they weren't actually in the document while they were being unit-tested.

So to fix it I added the following before your compile(elm)($scope);

angular.element('body').append(elm);

And then to clean up:

afterEach(function () {
    angular.element(elm).remove();
});

I don't know if it was intentional or not, but you called $new() on $rootScope in the first unit test but didn't use the result of that to compile with, whereas you did it in the second.

Upvotes: 2

Related Questions