简体   繁体   English

如何使用Karma在AngularJS控制器中测试$元素?

[英]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. 我有一个问题,我在我的应用程序中有一个控制器,我使用像<div ng-controller='LogbookEditCtrl'> </div> ,这个控制器有一个$元素提供程序,我需要修改元素。

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 : 我尝试了类似下面的内容,但它再次说没有找到$ element提供程序:

beforeEach(inject(function(_$element_) {
  var element = compile('<div></div>');
  $element = element;
}));

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). 并且没有角$element可用的$element提供者(非常类似于$scope因为它们是app注入器提供的动态特殊依赖项)。 You could create an element object using angular.element and pass it in as locals to the controller constructor,something like this. 您可以使用angular.element创建一个元素对象,并将其作为locals传递给控制器​​构造函数,如下所示。

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. 这开启了这样一个事实:为什么不建议在控制器中使用$element并在其中执行任何DOM操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM