Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test $element in AngularJS controller using Karma?

I am having a problem were I have a controller in my app which I use like <div ng-controller='LogbookEditCtrl'> </div> and this controller has a $element provider in it which I need to modify the element.

describe('LogbookEditCtrl', function(){
  'use strict';

  beforeEach(module('logbooks.edit'));


  it('should create "logbook" model', inject(function($controller) {
    var scope = {},

    // THIS EXPLODES BECAUSE IT SAYS THE $element PROVIDER WAS NOT FOUND, because there
    // is no html element of course..the controller is being created on its own.
    ctrl = $controller('LogbookEditCtrl', {$scope: scope});

  }));

});

I have tried something like the following, but it again says the $element provider was not found :

beforeEach(inject(function(_$element_) {
  var element = compile('<div></div>');
  $element = element;
}));
like image 697
Bryan Arbelo - MaG3Stican Avatar asked Jul 09 '15 00:07

Bryan Arbelo - MaG3Stican


People also ask

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

How pass data from controller controller to AngularJS?

Approach: To share data between the controllers in AngularJS we have two main cases: Share data between parent and child: Here, the sharing of data can be done simply by using controller inheritance as the scope of a child controller inherits from the scope of the parent controller.


1 Answers

You would need to pass that dependency itself, since it refers to the bound element of the controller. And there is no $element provider available in angular (much similar to $scope as these are dynamic special dependencies provided by the app injector). You could create an element object using angular.element and pass it in as locals to the controller constructor,something like this.

var scope = {}, 
    element = angular.element('<div></div>'); //provide element you want to test

ctrl = $controller('LogbookEditCtrl', {$scope: scope, $element:element });

This opens up the fact that why is it not recommended to use $element inside a controller and perform any DOM operation in them.

like image 123
PSL Avatar answered Oct 07 '22 18:10

PSL