首页 文章

Angular指令不在测试中链接

提问于
浏览
1

为了熟悉指令测试,我创建了如下所示的简单示例 . 不幸的是,测试失败了,似乎永远不会调用链接函数 . 该指令在应用程序中使用时确实有效 .

我试过硬编码 message 属性,删除链接函数中的条件,甚至从$ watch中提取attr集,但测试仍然失败 .

还有其他这样的帖子,其原因是由于缺少$ digest调用,但我确实有这个,我尝试将其移入 it spec块 .

如果我运行 console.log(elem[0].otherHTML) 调用,则范围绑定似乎有效

<wd-alert type="notice" message="O'Doole Rulz" class="ng-scope"></wd-alert>

我错过了什么?

alert.spec.js

"use strict";

describe('Alert Specs', function () {

  var scope, elem;

  beforeEach(module('myapp'));
  beforeEach(inject(function ($compile, $rootScope) {
    scope = $rootScope;
    scope.msg = "O'Doole Rulz";
    elem  = angular.element('<wd-alert type="notice" message="{{msg}}"></wd-alert>');
    $compile(elem)(scope);
    scope.$digest();
  }));

  it('shows the message', function () {
    expect(elem.text()).toContain("O'Doole Rulz");
  });

});

alert.js

angular.module('myapp').directive('wdAlert', function() {
  return  {
    restrict: 'EA',
    replace: true,
    template: '<div></div>',
    link: function(scope, element, attrs) {
      attrs.$observe('message', function() {
        if (attrs.message) {
          element.text(attrs.message);
          element.addClass(attrs.type);
        }
      })
    }
  }

});

2 回答

  • 0

    原来这个问题是我组织文件的方式的Karma配置 . 我会留下这个问题,万一它咬了别人的屁股 .

    files: [
      ...,
      'spec_path/directives/*js'      // what I originally had
      'spec_path/directives/**/*.js'  // what I needed
    ]
    
  • 0

    我正在添加此内容以扩展其他任何想要了解的人的答案 .

    我通过凉亭安装了第三方指令 . 它在应用程序中工作,但导致测试中断 .

    问题是Grunt / Karma没有读取index.html中的脚本 . 相反,你需要确保让业力知道每个已安装的脚本 .

    例如,我使用了指令ngQuickDate(一个datepicker) . 我将它添加到index.html for app,但我还需要将它添加到karma.conf.js:

    files: [
        ...
        'app/bower_components/ngQuickDate/dist/ng-quick-date.js'
    ]
    

    通过使用 ** 通配符来表示"in all subdirectories recursively",上面的答案也是一样的 .

    希望有所帮助!

相关问题