在Jasmine测试中模拟angular.element

14

我在一个控制器中有一个函数,其中包含一个调用

var someVar = angular.element(event.target).scope().field;

我正在尝试通过这样做来模拟它

var ngElementFake = function(el) {
                return {
                    scope: function() {
                        return {
                            toggleChildElement: true,
                            field: scope.field
                        }
                    }
                }
            }

spyOn(angular, 'element').andCallFake(ngElementFake);

然而,当我在测试中调用该函数时,我收到了以下响应:

TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')
at ../angular-mocks/angular-mocks.js:1819

我做错了什么?

编辑:注入

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

            scope = $rootScope;

            scope.record = recordData;

            scope.model = 'Hierarchy';

            ctrl = $controller("fngHierarchyChildCtrl", {
                $scope: scope
            });
        });
    });
3个回答

18

我通过手动在回调函数中清除间谍(spy)来解决了这个问题。

var spy;

beforeEach(function() {
    spy = spyOn(angular, 'element').andCallFake(ngElementFake);
});

afterEach(function() {
    spy.andCallThrough();
});

不错,对我有效。 - ganta
重要的一行是 spy.andCallThrough(); - Daniel
如何模拟 angular 对象? - Sonali

1

来自AngularJS FAQ

由于使用on()/off()而不是bind()/unbind()的更改,Angular 1.2仅与jQuery 1.7.1或更高版本配合使用。

因此,请尝试升级到1.7.1或更高版本的jquery,或者根本不使用jquery,而是使用Angular自己的jQLite。


0

当我从Angular 1.0.8切换到1.2.0时,在运行测试时遇到了以下错误:

TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')

TypeError: 'undefined' is not a function (evaluating '$rootElement.on')

解决方案是编辑karma配置文件中的文件部分,并将jQuery移动到angular下面:
 files: [
  //was here
  'http://code.angularjs.org/1.2.0/angular.js',
  'http://code.angularjs.org/1.2.0/angular-mocks.js',
  'http://code.angularjs.org/1.2.0/angular-resource.js',
  'http://code.angularjs.org/1.2.0/angular-route.js',
  'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', //moved to here
  ...
 ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接