0

我已选择根据以下问题的已接受答案中的选项 2 创建解决方案: Unit-testing directive controllers in Angular without making controller global

我的代码看起来像这样:

(function () {

    function myCtrl($scope) {
        //All my controller code.
    };

    myAppModule.directive('myDirective', function($compile, $timeout) {

        return {

            restrict: 'E',

            replace: true,

            controller: myCtrl,

            compile: function(tElement, tAttrs, transclude) {

                return {
                post: function(scope, element, attrs) {
                    //more code and stuff.
                }
            }
        }
    });
})();

我的简单问题是;因为控制器没有定义在模块的范围内,我如何将它加载到我的测试文件中?

4

1 回答 1

0

正如答案所解释的,您必须将上面的代码拆分为三个文件:

  • 所有代码的前缀function myCtrl($scope) {
  • 控制器代码
  • 后缀

在构建应用程序时,您将这三个文件合并为一个,并将结果用于生产代码。

对于测试,您只需包含中间文件。这确实会在测试的全局命名空间中创建您的控制器。在生产代码中,闭包避免了这种污染。

于 2013-10-17T08:31:11.830 回答