Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
            });
        });
    });
like image 468
Stevo Avatar asked Oct 18 '13 10:10

Stevo


People also ask

How do you mock an Angular component?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

How do you mock variable in Jasmine?

First define a variable like this: let authService: AuthService; Then once the testbed has been set up, set this to the actual service being used by the TestBed inside the last beforeEach() : authService = TestBed.

How an Angular component is tested using the Jasmine test framework?

To run your tests using the Angular CLI, you use the ng test command in your terminal. As a result, Karma will open up the default browser and run all the tests written with the aid of Jasmine and will display the outcome of those tests.

What is mock in Angular unit testing?

Mocking is the act of creating something that looks like the dependency but is something we control in our test. There are a few methods we can use to create mocks.


2 Answers

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();
});
like image 173
jrubio Avatar answered Sep 20 '22 10:09

jrubio


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.

like image 31
Jeremy Avatar answered Sep 22 '22 10:09

Jeremy