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


i have directive uses isolate scope pass in data directive changes on time. watches changes on value , computation on each change. when try unit test directive, can not watch trigger (trimmed brevity, basic concept 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 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 csv', function() {     scope.input = somedata;     var e = $compile('<file data="input" filename="filename.csv"></file>')(scope);     //i've tried below not     scope.$apply(function() { scope.input = {}; });   }); 

what can trigger watch "in watch" debugging statement triggered? "in link" gets triggered when compile.

for $watch triggered, digest cycle must occur on scope defined or on parent. since directive creates isolate scope, doesn't inherit parent scope , watchers won't processed until call $apply on proper scope.

you can access directive scope calling scope() on element returned $compile service:

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

this jsfiddler exemplifies that.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -