Stevo
Stevo

Reputation: 2639

Mock out angular.element in Jasmine tests

I have a function in a controller that has a call

var someVar = angular.element(event.target).scope().field;

I am trying to mock it by doing

var ngElementFake = function(el) {
                return {
                    scope: function() {
                        return {
                            toggleChildElement: true,
                            field: scope.field
                        }
                    }
                }
            }

spyOn(angular, 'element').andCallFake(ngElementFake);

However when I call the function in the test I get the response:

TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')
at ../angular-mocks/angular-mocks.js:1819

What am I doing wrong?

EDIT: Injection

    beforeEach(function() {
        inject(function($rootScope, $controller) {

            scope = $rootScope;

            scope.record = recordData;

            scope.model = 'Hierarchy';

            ctrl = $controller("fngHierarchyChildCtrl", {
                $scope: scope
            });
        });
    });

Upvotes: 14

Views: 14530

Answers (3)

jrubio
jrubio

Reputation: 206

I was able to fix this by manually clearing the spy in an after callback.

var spy;

beforeEach(function() {
    spy = spyOn(angular, 'element').andCallFake(ngElementFake);
});

afterEach(function() {
    spy.andCallThrough();
});

Upvotes: 17

Jeremy
Jeremy

Reputation: 6723

From the AngularJS FAQ:

Due to a change to use on()/off() rather than bind()/unbind(), Angular 1.2 only operates with jQuery 1.7.1 or above.

So, try upgrading to jquery 1.7.1 or above or don't use jquery at all and angular will use its own jQLite.

Upvotes: 1

M J
M J

Reputation: 4327

When switching from angular 1.0.8 to 1.2.0, I experienced the following errors when running my tests:

TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')

TypeError: 'undefined' is not a function (evaluating '$rootElement.on')

The solution was to edit the files section of the karma configuration and move jQuery below angular:

 files: [
  //was here
  'http://code.angularjs.org/1.2.0/angular.js',
  'http://code.angularjs.org/1.2.0/angular-mocks.js',
  'http://code.angularjs.org/1.2.0/angular-resource.js',
  'http://code.angularjs.org/1.2.0/angular-route.js',
  'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', //moved to here
  ...
 ]

Upvotes: 0

Related Questions