nathasm nathasm - 1 year ago 81
AngularJS Question

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

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(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.

Answer Source

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

This jsFiddler exemplifies that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download