在AngularJS中注入$ attrs

use*_*277 9 unit-testing jasmine angularjs

我在AngularJS的上下文中编写了一些JavaScript.我的相关JavaScript如下所示:

.factory('$myFactory', function ($myLibrary, $interpolate) {
 return {
   myFunction: function ($scope, $attrs, p) {
     if (p !== null) {
       $attrs.set('myProperty', p);
     }
   }
 };
Run Code Online (Sandbox Code Playgroud)

我正在尝试对此代码进行单元测试.为了对代码进行单元测试,我正在使用Jasmine.

it('should set myProperty', inject(function ($scope, $myFactory) {
//  $myFactory.myFunction($scope
}));
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何从我的单元测试中注入一些$ attrs.我怎么做?我可以成功获得我的$ scope设置.但是,我不明白如何注入$ attrs.我不知道有什么特别之处吗?我遇到了与$ element类似的问题,尽管那个问题超出了这个特定测试的范围.

谢谢!

Ila*_*mer 9

这是一个吸烟者:http://plnkr.co/edit/k1cxSjpAXhhJUEOcx9PG

也许有更好的解决方案,但这就是我得到的.

  • $scope很容易得到,你可以$rootScope随处注入
  • $attrs另一方面只能通过$compile变量(它存在于compile.js中)

我的解决方案是创建一个假控制器,编译它并劫持它$attrs.

这就是它的样子:

var injected = null

function fakeController($scope, $attrs, $element){
  injected = {}
  injected.$scope = $scope;
  injected.$attrs = $attrs;
  injected.$element = $element;
}

describe('Testing a Hello World controller', function() {
  var $scope = null;
  var $attrs = null;
  var $element = null;

  var ctrl = null;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));

  beforeEach(inject(function($compile, $rootScope, $controller) {

    $compile('<span ng-controller="fakeController"></span>')($rootScope);

    $scope = injected.$scope;
    $attrs = injected.$attrs;
    $element = injected.$element;

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

  }));

  it('should say hallo to the World', function() {
    expect($scope.name).toEqual('World');
  });
});
Run Code Online (Sandbox Code Playgroud)


jaf*_*af0 5

似乎你可以用空对象实例化控制器,以及......

ctrl = $controller('MyCtrl', {
  $scope: $scope,
  $attrs: {}
});
Run Code Online (Sandbox Code Playgroud)