【问题标题】:AngularJS testing directives with templateUrlAngularJS 使用 templateUrl 测试指令
【发布时间】:2014-04-28 18:00:50
【问题描述】:

我正在尝试使用 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();
});

【问题讨论】:

    标签: javascript angularjs angularjs-directive karma-runner


    【解决方案1】:

    根据url(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

    【讨论】:

    • 这似乎在大多数情况下都有效,但奇怪的是我的指令仍然不喜欢templateUrl。如果我使用template: $templateCache.get('...'),,它工作得很好。关于我可能做错的任何想法?
    • 您看到GET 请求失败并返回 404 吗?检查你的 karma 配置文件中的 basePath 设置。
    猜你喜欢
    • 2013-01-23
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多