单元测试的AngularJS指令与分离范围手表的属性 [英] Unit testing an AngularJS directive that watches an an attribute with isolate scope

查看:78
本文介绍了单元测试的AngularJS指令与分离范围手表的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用范围隔离在数据传递到随时间变化指令一个指令。这手表上的修改,确实每个改变一些计算。当我尝试单元测试指令,我不能让手表触发(修剪简洁,但基本概念如下图所示):

I have a directive that uses an isolate scope to pass in data to a directive that changes over time. It watches for changes on that value and does some computation on each change. When I try to unit test the directive, I can not get the watch to trigger (trimmed for brevity, but the basic concept is shown below):

指令:

angular.module('directives.file', [])
.directive('file', function() {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      filename: '@',
    },
    link: function(scope, element, attrs) {
      console.log('in link');
      var convertToCSV = function(newItem) { ... };

      scope.$watch('data', function(newItem) {
        console.log('in watch');
        var csv_obj = convertToCSV(newItem);
        var blob = new Blob([csv_obj], {type:'text/plain'});
        var link = window.webkitURL.createObjectURL(blob);
        element.html('<a href=' + link + ' download=' + attrs.filename +'>Export to CSV</a>');
      }, true);
    }
  };
});

测试:

describe('Unit: File export', function() {
  var scope;

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

  it('should create a CSV', function() {
    scope.input = someData;
    var e = $compile('<file data="input" filename="filename.csv"></file>')(scope);
    //I've also tried below but that does not help
    scope.$apply(function() { scope.input = {}; });
  });

我能做些什么来触发手表,所以我的手表调试语句被触发?我的在链接被当我编译触发。

What can I do to trigger the watch so my "In watch" debugging statement is triggered? My "In link" gets triggered when I compile.

推荐答案

对于 $观看来被触发,必须在它被定义的范围会发生消化周期或其父。由于您的指令创建一个隔离的范围,它不从父继承的范围,因此,其观察家不会得到处理,直到你调用 $适用在适当范围。

For a $watch to get triggered, a digest cycle must occur on the scope it is defined or on its parent. Since your directive creates an isolate scope, it doesn't inherit from the parent scope and thus its watchers won't get processed until you call $apply on the proper scope.

您可以通过调用访问指令范围范围() $编译服务返回的元素:

You can access the directive scope by calling scope() on the element returned by the $compile service:

scope.input = someData;
var e = $compile('<file data="input" filename="filename.csv"></file>')(scope);
e.scope().$apply();

jsFiddler 体现了这一点。

这篇关于单元测试的AngularJS指令与分离范围手表的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆