javascript Angular Karma 测试在 $scope.$parent 函数上得到“TypeError: 'undefined' is not a function”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18385842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:43:05  来源:igfitidea点击:

Angular Karma Test getting "TypeError: 'undefined' is not a function" on a $scope.$parent function

javascriptangularjs

提问by Sartaj

While running grunt teston a Yeoman (1.0RC1) scaffolded Angular (1.0.7) app, I'm getting the following error:

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

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

userLoggedIn()is within a parent controller index.js. The function itself runs fine within the angular app.

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

This error doesn't occur on my other $scope.$parentboolean or strings variables in the controller, so it's related directly to calling functions within a parent.

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

I'm thinking that I'm either using $scope.$parentthe wrong way or that I need to define my index.jscontroller in the test, but Karma testing documentation is sporadic, so it's hard to know.

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

EDIT: Here is the controller:

编辑:这是控制器:

'use strict';

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

    $scope.$parent.userLoggedIn(true);

  }]);

Here is the test:

这是测试:

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

});

(Yes I know I'm just using the default awesomeThingstest for now. I'm new to Angular testing).

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

采纳答案by Ven

You're giving the controller a rootScope, which doesn't have $parent(it's the root). Change your controller code to call it correctly (using the prototype chain) and you'll be fine by just passing {my: props}as an object.

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