使用templateUrl的AngularJS测试指令

时间:2014-04-28 18:00:51

标签: javascript angularjs angularjs-directive karma-runner

我正在尝试使用karma来测试AngularJS指令。但是我遇到了templateUrls的问题。使用here描述的技术,它变得更加奇怪。它看起来像宣传的那样工作,并将我的模板加载到$ templateCache中,但该指令没有使用该缓存。这是一些代码:

这样可以正常使用

.directive('messageComposer', function($templateCache) {
  return {
    restrict: 'E',
    template: $templateCache.get('partials/message_composer.html'),
    replace: true,
    link: function() {
      console.log('hello world');
    }
  };
});

但是一旦我使用templateUrl,它就无法在测试中绑定:

.directive('messageComposer', function() {
  return {
    restrict: 'E',
    templateUrl: 'partials/message_composer.html',
    replace: true,
    link: function() {
      console.log('hello world');
    }
  };
});

任何人都知道这里发生了什么?

这是我的单元测试设置:

var $scope;
var $compile;

beforeEach(function() {
    module('partials/message_composer.html');
    module('messageComposer');

    inject(function(_$compile_, $rootScope) {
        $scope = $rootScope.$new();
        $compile = _$compile_;
    });  
});


it("works", function() {
    $scope.message = {};
    elem = angular.element("<message-composer message='message'></message-composer>")
    $compile(elem)($scope);

    console.log(elem);

    expect(true).toBeDefined();
});

1 个答案:

答案 0 :(得分:1)

根据网址(http://tylerhenkel.com/how-to-test-directives-that-use-templateurl/),我相信你已经运行了以下命令:

npm install karma-ng-html2js-preprocessor --save-dev

现在,当您使用上述预处理器时,此预处理器将HTML文件转换为JS字符串并生成Angular模块。这些模块在加载时会将这些HTML文件放入$ templateCache中,因此Angular不会尝试从服务器中获取它们。

希望,以下文件将更好地澄清您:

https://github.com/karma-runner/karma-ng-html2js-preprocessor https://github.com/vojtajina/ng-directive-testing

相关问题