How do you mock directives to enable unit testing of higher level directive?

前端 未结 7 1847
故里飘歌
故里飘歌 2020-12-04 09:05

In our app we have several layers of nested directives. I\'m trying to write some unit tests for the top level directives. I\'ve mocked in stuff that the directive itself ne

7条回答
  •  无人及你
    2020-12-04 09:19

    Being forced to think about this more myself, I have come up with a solution that fills our needs. All of our directives are attributes, so I created an attributeRemover directive for use during the unit tests. It looks something like this:

    angular.module("myModule").directive("attributeRemover", function() {
        return {
            priority: -1, //make sure this runs last
            compile: function(element, attrs) {
                var attributesToRemove = attrs.attributeRemover.split(",");
                angular.forEach(attributesToRemove, function(currAttributeToRemove) {
                    element.find("div[" + currAttributeToRemove + "]").removeAttr(currAttributeToRemove);
                });
            }
        }
    });
    

    Then the html for the directive I'm testing looks something like this:

    So, when my-higher-level-directive gets compiled the attribute-remover will have already removed the attributes for the lower level directives and thus I don't have to worry about what they are doing.

    There's probably a more robust way of doing this for all kinds of directives (not just attribute ones) and I'm not sure if this works if only using the built-in JQLite, but it works for what we need.

提交回复
热议问题