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

前端 未结 7 1836
故里飘歌
故里飘歌 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:25

    Due to the implementation of the directive registration, it does not seem possible to replace an existing directive by a mocked one.

    However, you have several ways to unit test your higher level directive without interference from lower level directives :

    1) Do not use lower level directive in your unit test template :

    If your lower level directive is not added by your higher level directive, in your unit test use a template with only you higer-level-directive :

    var html = "
    "; $compile(html)(scope);

    So, lower level directive will not interfere.

    2) Use a service in your directive implementation :

    You can provide the lower level directive linking function by a service :

    angular.module("myModule").directive("myLowerLevelDirective", function(myService) {
        return {
            link: myService.lowerLevelDirectiveLinkingFunction
        }
    });
    

    Then, you can mock this service in your unit test to avoid interference with your higher level directive. This service can even provide the whole directive object if needed.

    3) You can overwrite your lower level directive with a terminal directive :

    angular.module("myModule").directive("myLowerLevelDirective", function(myService) {
        return {
            priority: 100000,
            terminal: true,
            link: function() {
                // do nothing
            }
        }
    });
    

    With the terminal option and a higher priority, your real lower level directive will not be executed. More infos in the directive doc.

    See how it works in this Plunker.

提交回复
热议问题