Given the following directive:

angular('ngTestLib').directive('test', function(TestService) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs, controller) {
      TestService.serve(function() {
        console.log('element in directive:', elem);
        elem.addClass('test');
      });
    }
  };
});

And the following unit test:

describe('Testing test directive', function () {
  var element, scope, serviceMock;

  beforeEach(function() {
    angular.module('ngTestMock', [])
      .service('TestService', function() {
        serviceMock= this;
        this.serve=function(h) {
          serviceMock.handler= h;
        };
      });

    angular.module('Test', ['ngTestLib', 'ngTestMock'])
  });

  beforeEach(module('Test'));

  var template= '<div test></div>';

  function compile(template) {
    inject(function($compile, $rootScope) {
      var linkingFn = $compile(template);
      element= linkingFn($rootScope.$new());
      scope= element.isolateScope();
    });
  };

  it('should call addClass', function() {
    compile(template);
    console.log('element in spec:', element);
    spyOn(element, 'addClass');
    console.log('element in spec:', element);
    serviceMock.handler();
    expect(element.addClass).toHaveBeenCalled();
  });

});

I get the following output when running the unit test:

LOG: 'element in spec:', Object{0: <div test="" class="ng-scope"></div>, 
length: 1} // element
LOG: 'element in spec:', Object{0: <div test="" class="ng-scope"></div>, 
length: 1, addClass: function () { ... }} // spy added
LOG: 'element in directive:', Object{0: <div test="" 
class="ng-scope"></div>, length: 1} // no spy present in the directive
PhantomJS 1.9.7 (Mac OS X) Testing test directive should call addClass 
FAILED
Expected spy addClass to have been called.
PhantomJS 1.9.7 (Mac OS X): Executed 8 of 8 (1 FAILED) (0.033 secs / 0.062 
secs)

For some reason the spy I'm putting on the element in the spec file does 
not exists on the element object in the directive. Can anyone see what I'm 
doing wrong? Why are the two elements not the same object?

mg

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to