AngularJS/Karma - 指令中的单元测试功能

标签 angularjs unit-testing jasmine karma-runner directive

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

指示:

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");
  });
});

最佳答案

您错过了对 module 的调用.

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

Note: Said default was introduced in angular-1.3.0(commit: 11f5ae, PR: 8321), prior to that version it was simply 'A'. Which would have been an issue in your case, seeing as how your question was posted in May'14.



我设置了一个 fiddle 来展示你的实现,有两个变化;
  • 调用 module ,以便加载您的指令定义。
  • 将 Angular 版本撞到 1.3.0 .

  • jsFiddle

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

    关于AngularJS/Karma - 指令中的单元测试功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826416/

    相关文章:

    javascript - 不再能够使用 ddescribe 或 iit

    javascript - 用户界面路由器 : Transform parameter from URL

    javascript - AngularJs:相对路径不使用 $location.path 重定向

    javascript - Angularjs 与 # 导航链接中的 jquery 插件相关的问题

    android - 如何告诉被测对象使用模拟而不是它自己的变量

    unit-testing - 由于错误,无法测试我的 grails 应用程序

    javascript - Angularjs 指令内容未链接到隔离范围

    c++ - GMock 将一个模拟对象传递给另一个对象,调用 stub 方法仍然是调用真实逻辑

    testing - 有没有一种方法可以对 Jasmine 测试进行分类并管理排除项

    unit-testing - 无法在 PhantomJS 浏览器中执行 karma 单元测试