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

Upvotes: 11

Views: 9987

Answers (1)

PSL
PSL

Reputation: 123739

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.

Upvotes: 27

Related Questions