Mock out angular.element in Jasmine tests

14,289

Solution 1

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();
});

Solution 2

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.

Share:
14,289

Related videos on Youtube

Stevo
Author by

Stevo

Updated on September 14, 2022

Comments

  • Stevo
    Stevo over 1 year

    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
                });
            });
        });
    
  • ganta
    ganta over 8 years
    Good one. Works for me
  • Daniel
    Daniel about 8 years
    The important line is spy.andCallThrough();
  • Sonali
    Sonali over 5 years
    how to mock angular object?