【问题标题】:AngularJS/Karma - unit test function in directiveAngularJS/Karma - 指令中的单元测试功能
【发布时间】:2014-07-12 15:32:09
【问题描述】:

如何对指令链接中的函数进行单元测试?我尝试过这样的事情,但没有奏效:

指令:

app.directive("hello", function(){
  return {
    link: function(scope){
      scope.hello = function(){
        return "hello";
      };
    }
  };
});

单元测试:

describe("Hello directive", function(){
  var compile, scope;

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

  it("should return hello", function(){
    var element = compile("<hello></hello>")(scope);
    expect(element.scope.hello()).toBe("hello");
  });
});

【问题讨论】:

  • 定义“无效”。为什么使用element.scope.hello() 而不仅仅是scope.hello()?此外,element.scope 是一个返回元素范围的函数,如文档所述:docs.angularjs.org/api/ng/function/angular.element。所以应该是element.scope().hello()
  • 与 element.scope().hello() 的结果是一样的:“TypeError: 'undefined' is not a function (evalating 'element.scope().hello()')”
  • 还有 scope.hello()。
  • 你的指令没有被应用,因为它的默认限制是'A'。所以你需要&lt;div hello&gt;&lt;/div&gt; 来应用这个指令。如果您希望使用 &lt;hello&gt;&lt;/hello&gt; 应用指令,请将限制字段设置为“E”
  • 没错。另一个命令在测试中失败: beforeEach(module("myApp"));现在它正在工作。如果你把它写在答案中,我会接受。

标签: angularjs unit-testing jasmine karma-runner directive


【解决方案1】:

您错过了对module 的呼叫。

指令限制看起来很好(现在),因为根据angular source for $compileProvider,默认是'EA'

注意:所说的默认值是在 angular-1.3.0(commit: 11f5ae, PR: 8321) 中引入的,在该版本之前它只是 'A'。在您的情况下,这将是一个问题,看看您的问题是如何在 14 年 5 月发布的。

我设置了一个小提琴来展示您的实现,其中包含两个更改;

  • 调用module,以加载您的指令定义。
  • 将角度版本改为1.3.0

jsFiddle


是的,我迟到了,但你的问题仍然是 [angularjs]+[unit-testing] 中最重要的未回答问题之一。我想我会尝试改变它。

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2015-10-23
    • 2017-01-03
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多