【问题标题】:Angular Karma Test getting "TypeError: 'undefined' is not a function" on a $scope.$parent functionAngular Karma 测试在 $scope.$parent 函数上得到“TypeError:'undefined' is not a function”
【发布时间】:2013-08-23 03:39:53
【问题描述】:

在 Yeoman (1.0RC1) 脚手架 Angular (1.0.7) 应用程序上运行 grunt test 时,我收到以下错误:

TypeError: 'undefined' is not a function (evaluating '$scope.$parent.userLoggedIn(true)')

userLoggedIn() 在父控制器 index.js 中。该函数本身在 Angular 应用程序中运行良好。

此错误不会发生在我的其他 $scope.$parent 控制器中的布尔或字符串变量上,因此它与调用父级中的函数直接相关。

我在想我要么以错误的方式使用$scope.$parent,要么我需要在测试中定义我的index.js 控制器,但Karma 测试文档是零星的,所以很难知道。

编辑:这是控制器:

'use strict';

angular.module('uiApp')
  .controller('LookupCtrl', ['$scope', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.$parent.userLoggedIn(true);

  }]);

这是测试:

'use strict';

describe('Controller: LookupCtrl', function () {

  // load the controller's module
  beforeEach(module('uiApp'));

  var LookupCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    LookupCtrl = $controller('LookupCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });

});

(是的,我知道我现在只使用默认的 awesomeThings 测试。我是 Angular 测试的新手)。

【问题讨论】:

  • 能否提供测试控制器的代码。
  • 一般来说,这只是意味着您正在尝试使用属性名称来查找函数,但您正在使用的对象没有这样的属性。因此,您尝试将 undefined 用作函数,而它不是函数。

标签: javascript angularjs


【解决方案1】:

你给控制器一个rootScope,它没有$parent(它是根)。 更改控制器代码以正确调用它(使用原型链),只需将 {my: props} 作为对象传递就可以了。

【讨论】:

  • 我让它工作了,但我不确定我做得是否正确。我在测试中的 LookupCtrl 之前添加了我的 IndexCtrl 并在其中调用了根范围。
  • 我在测试中的LookupCtrl 之前添加了我的IndexCtrl,并在其中调用了var scope = $rootScope.$new()$scope: scope.$new()。之后,在LookupCtrl 中,我刚刚使用$scope: scope.$new() 制作了另一个新范围
  • 有人可以把小提琴放在一起吗?我无法理解这里的建议。
猜你喜欢
  • 1970-01-01
  • 2014-06-29
  • 2014-12-30
  • 2021-11-16
  • 2015-06-24
  • 2021-06-21
  • 1970-01-01
  • 2015-10-23
  • 2014-08-15
相关资源
最近更新 更多