title: Unit testing an AngularJS directive that watches an an attribute with isolate scope
body: <p>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):</p>
  
  <p><strong>Directive:</strong></p>
  
  <pre><code>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('&lt;a href=' + link + ' download=' + attrs.filename +'&gt;Export to CSV&lt;/a&gt;');
        }, true);
      }
    };
  });
  </code></pre>
  
  <p><strong>Test:</strong></p>
  
  <pre><code>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('&lt;file data="input" filename="filename.csv"&gt;&lt;/file&gt;')(scope);
      //I've also tried below but that does not help
      scope.$apply(function() { scope.input = {}; });
    });
  </code></pre>
  
  <p>What can I do to trigger the watch so my "In watch" debugging statement is triggered? My "In link" gets triggered when I compile.</p>