Unit testing an AngularJS directive that watches an an attribute with isolate scope

只愿长相守 提交于 2019-12-12 08:22:29

问题


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):

Directive:

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

Test:

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.


回答1:


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.isolateScope().$apply();

This jsFiddler exemplifies that.



来源:https://stackoverflow.com/questions/17979282/unit-testing-an-angularjs-directive-that-watches-an-an-attribute-with-isolate-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!