jeudi 11 août 2016

Angular - Jasmine: Testing immediatly invoked functions inside a directive controller

Suppose that I have a directive like:

.directive('myDir', function(TemplateHandler){
  return {
    ...
    controller: function(ExploreCmd){
      this.foo = {
        bar: function(){...}
      };

      this.foo.bar();
    }
  }
});

And I want to test that when the directive is loaded the this.foo.bar() function has been called, how can I achieve that?

I tried with:

beforeEach(inject(function($compile, $rootScope){
  scope = $rootScope.$new();
  element = angular.element('<js-shell></js-shell>');
  $compile(element)(scope);
  scope.$digest();
  isolatedScope = element.isolateScope().vm;
  spyOn(isolatedScope.foo, 'bar');
}));

it('should register the explore command', () => {
  expect(isolatedScope.foo.bar).toHaveBeenCalled();
});

But the problem is that spyOn(isolatedScope.foo, 'bar'); is called after the isolatedScope.foo.bar has been called, so the test fail.

Any idea on how to solce?

Aucun commentaire:

Enregistrer un commentaire