gpt4 book ai didi

angularjs - 在 AngularJS 中注入(inject) $attrs

转载 作者:行者123 更新时间:2023-12-02 22:09:00 25 4
gpt4 key购买 nike

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

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

我正在尝试对这段代码进行单元测试。为了尝试对代码进行单元测试,我使用了 Jasmine。

it('should set myProperty', inject(function ($scope, $myFactory) {
// $myFactory.myFunction($scope
}));

我不知道如何从单元测试中注入(inject)一些 $attrs。我怎么做?我可以成功获得我的 $scope 设置。但是,我不明白如何注入(inject) $attrs。难道有什么我不知道的特别之处吗?我对 $element 也有类似的问题,尽管这个问题超出了这个特定测试的范围。

谢谢!

最佳答案

这是一个骗子:http://plnkr.co/edit/k1cxSjpAXhhJUEOcx9PG

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

  • $scope很容易获取,你可以在任何地方注入(inject)$rootScope
  • 另一方面,
  • $attrs 只能通过 $compile 变量使用(它位于 compile.js )

我的解决方案是创建一个假 Controller 编译它并劫持它的$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');
});
});

关于angularjs - 在 AngularJS 中注入(inject) $attrs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21313181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com