Jimi
Jimi

Reputation: 1897

Jasmine unit testing directives with external dependencies fails with TypeError: '[object Object]'

I'm getting an error from my spec when I run it. I'm testing a directive that includes this service. The test is returning an error message:

TypeError: '[object Object]' is not a function (evaluating 'angular('RecursionHelper')').

Not sure what I'm missing in order for this to work. I'm using Angular 1.3 & Jasmine 2.0.

my directive:

return RecursionHelper.compile(element, function (scope, Element, Attrs,     contro, transFn) {
   //directive functions
});

My spec:

   beforeEach(function () {
       angular('RecursionHelper');
   });

  element = angular.element('<directive></directive>');
            $scope.directiveList = directiveList;
            RecursionHelper.compile(element)($scope);
            $scope.$digest();

Upvotes: 2

Views: 230

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12862

In beforeEach block, you should load your app module, which contains the directive. Change:

beforeEach(function () {
    angular('RecursionHelper');
});

To:

beforeEach(function () {
    module('MyApp'); //change to your application name. 
});

Also, you should inject $compile service and $rootScope before each jasmine test. You are using compile service to render the directive without injecting it.

Just add to your beforeEach:

inject(function($compile, $rootScope, $injector) {
    compile = $compile;
    $scope = $rootScope.$new();
});

Final code should look like:

   beforeEach(function () {
       module('MyApp'); //change to your application name.
       inject(function($compile, $rootScope, $injector) {
           compile = $compile;
           $scope = $rootScope.$new();
       }); 
   });    


it('make an assertion', function() {
    var element = angular.element('<directive></directive>');
    $scope.directiveList = directiveList;
    compiledElement = compile(element)($scope);
    $scope.$digest();
});

Upvotes: 2

Related Questions