title: How to Unit Test Isolated Scope Directive in AngularJS
body: <p>What is a good way to unit test isolated scope in AngularJS</p>
  
  <p><a href="http://jsfiddle.net/daniellmb/b7BRR">JSFiddle showing unit test</a></p>
  
  <p>Directive snippet</p>
  
  <pre><code>    scope: {name: '=myGreet'},
      link: function (scope, element, attrs) {
          //show the initial state
          greet(element, scope[attrs.myGreet]);
  
          //listen for changes in the model
          scope.$watch(attrs.myGreet, function (name) {
              greet(element, name);
          });
      }
  </code></pre>
  
  <p>I want to ensure the directive is listening for changes - this does <strong>not</strong> work with an isolated scope:</p>
  
  <pre><code>    it('should watch for changes in the model', function () {
          var elm;
          //arrange
          spyOn(scope, '$watch');
          //act
          elm = compile(validHTML)(scope);
          //assert
          expect(scope.$watch.callCount).toBe(1);
          expect(scope.$watch).toHaveBeenCalledWith('name', jasmine.any(Function));
      });
  </code></pre>
  
  <p><strong>UPDATE:</strong>
  I got it to work by checking if the expected watchers were added to the child scope, but it's very brittle and probably using the accessors in an undocumented way (aka subject to change without notice!).</p>
  
  <pre><code>//this is super brittle, is there a better way!?
  elm = compile(validHTML)(scope);
  expect(elm.scope().$$watchers[0].exp).toBe('name');
  </code></pre>
  
  <p><strong>UPDATE 2:</strong>
  As I mentioned this is brittle! The idea still works but in newer versions of AngularJS the accessor has changed from <code>scope()</code> to <code>isolateScope()</code>:</p>
  
  <pre><code>//this is STILL super brittle, is there a better way!?
  elm = compile(validHTML)(scope);                       
  expect(elm.isolateScope().$$watchers[0].exp).toBe('name');
  </code></pre>