【问题标题】:Mock out angular.element in Jasmine tests在 Jasmine 测试中模拟 angular.element
【发布时间】:2013-10-27 04:18:24
【问题描述】:

我在一个控制器中有一个函数,它有一个调用

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

【问题讨论】:

    标签: unit-testing angularjs jasmine


    【解决方案1】:

    我可以通过在回调后手动清除间谍来解决此问题。

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

    【讨论】:

    • 好一个。为我工作
    • 重要的一行是spy.andCallThrough();
    • 如何模拟angular对象?
    【解决方案2】:

    来自 AngularJS FAQ:

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

    所以,请尝试升级到 jquery 1.7.1 或更高版本,或者根本不使用 jquery,Angular 将使用自己的 jQLite。

    【讨论】:

      【解决方案3】:

      从 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
        ...
       ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 2013-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多