【问题标题】:AngularJS Karma Jasmine Testing Directive Fails because of $compile?AngularJS Karma Jasmine 测试指令因 $compile 而失败?
【发布时间】:2015-11-12 01:42:18
【问题描述】:

我正在使用 Jasmine 为 angularJS 中的指令编写测试。在 karma.conf.js 中,我包含了所有依赖项和模块的路径。我正在使用的指令非常复杂,因此我借用了一些简单的自定义指令代码进行测试。它在我的应用程序中的 js fiddle 和指令函数中运行良好,但它在我的应用程序中未通过以下测试:

我的规范看起来像这样:

describe('Unit testing: ', function() {
  var $compile,
      $rootScope;

 beforeEach(module('app.directives'));  // our directives

  // Store references to $rootScope and $compile
  // so they are available to all tests in this describe block
  beforeEach(inject(function(_$compile_, _$rootScope_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('Replaces the element with the appropriate content', function() {
    // Compile a piece of HTML containing the directive
    var element = $compile("<div hello-world></div>")($rootScope);

    // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
    $rootScope.$digest();

    // Check that the compiled element contains the templated content
    expect(element.html()).toContain("Hello World!");
  });
});

指令如下所示:

angular.module('app.directives')
.directive('helloWorld', function() {
  return {
      restrict: 'AE',
      template: '<h3>Hello World!!</h3>'
  };
});

当我运行 grunt karma 时,最后一个测试失败了,因为:

Firefox 40.0.0 (Mac OS X 10.10.0) Unit testing:  Replaces the element with the appropriate content FAILED
    Expected '' to contain 'Hello World!'.

我在插入一些 console.log 语句时看到的主要问题是,在我调用 $compile 之后(或在 $digest 之后)指令没有正确编译:

Firefox 40.0.0 (Mac OS X 10.10.0) LOG: {0: <div class="ng-scope" hello-world=""></div>, length: 1}

我很困惑。我知道我可能需要提供有关我的应用程序的更多信息,但简而言之,这种解释是我的核心问题。

[编辑]:创建一个新模块可以快速解决这个问题,但问题仍然是当单个模块中有多个指令时如何处理指令单元测试(仍然失败)。

【问题讨论】:

  • 你的指令名称是 "mmsHelloWorld" 那么你的模板不应该看起来像&lt;div mms-hello-world&gt;&lt;/div&gt;吗?即,您缺少 mms- 前缀
  • mms 只是特定于我正在处理的应用程序的命名约定。我试图概括代码并使其更直观,所以我删除了它,但显然不是全部!对不起!
  • 你的指令名称应该是 "helloWorld",而不是 "HelloWorld" 虽然我不完全确定前导大写字母是否有区别但比抱歉更安全:)
  • 你是对的,但这也是命名约定编辑的一部分。在发布代码之前我应该​​更加注意:(。
  • 啊,我是replace: 'false''false' 字符串的计算结果为 true。要么设置replace: false,要么完全省略replace(反正它已经被弃用了)

标签: angularjs jasmine karma-runner


【解决方案1】:

(已编辑答案) 一旦我确定你的代码正确地包含在我的 karma.conf.js 中,你的代码就对我有用。

files: [
    "include/path/to/your/directive/file.js",
    "include/path/to/your/directive/test.js"
]

【讨论】:

  • 好建议,但内部 html 仍然是空的。我也尝试了 angular.element 方法。
  • 所以这个问题与建议的业力配置文件有关。必须重构文件的顺序、依赖项和构建目录才能使其正常工作。
猜你喜欢
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 2017-02-26
  • 1970-01-01
  • 2014-05-04
  • 2021-10-08
  • 1970-01-01
相关资源
最近更新 更多