gpt4 book ai didi

javascript - Angular 单元测试 : Calling a method defined in another controller is throwing 'undefined' is not an error

转载 作者:行者123 更新时间:2023-12-03 23:54:28 27 4
gpt4 key购买 nike

我正在尝试测试 AngularJS 文件,但它无法调用另一个 Controller 中定义的方法。

在我的页面文件中:

angular.module('MyApplication').controller('MyPageCtrl', function ($scope, $rootScope) {
if($scope.pageChecker) {
$scope.doSomething();
}
}

pageChecker() 方法在 App.js 中定义,在 MyApplication Controller 中,并返回 true 或 false。

为了完整起见:

$scope.pageChecker = function() {
if(cookieCheck) {
return true;
}
else {
return false;
}
};

Jasmine 文件是:

describe("Page check", function(){
beforeEach(angular.mock.module('MyApplication'));

beforeEach(angular.mock.inject(function ($rootScope, $controller) {
var $scope = $rootScope.$new();
$controller('MyPageCtrl', { $scope: $scope});
}));

it("should call $scope.doSomething", function(){
spyOn($scope, "doSomething");
$scope.doSomething();
expect($scope.doSomething).toHaveBeenCalled();
});
});

我得到“TypeError:‘undefined’不是一个函数(评估‘$scope.pageChecker()’)

我想覆盖 pageChecker 方法以始终返回 true。我该怎么做?

编辑:感谢 Dskh,我得到了我的答案,还有我的另一个调整:

describe("Page check", function(){

var $scope; //declare here, else it is a local variable inside the beforeEach

beforeEach(angular.mock.module('MyApplication'));

beforeEach(angular.mock.inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
// define the overriding methods here
$scope.pageChecker = function(){
return true;
};
// end overriding methods here
$controller('MyPageCtrl', { $scope: $scope});
}));

it("should call $scope.doSomething", function(){
spyOn($scope, "doSomething");
$scope.doSomething();
expect($scope.doSomething).toHaveBeenCalled();
});
});

最佳答案

当你执行 $rootScope.$new() 时,你自己创建了 $scope,然后当你使用 $controller() 方法时,你将它注入(inject)到你创建的 Controller 中。

因此,如果你想让那个方法总是返回true,你只需要自己创建这个方法:

beforeEach(angular.mock.inject(function ($rootScope, $controller) {
var $scope = $rootScope.$new();

$scope.doSomething = function(){
return true;
};

$controller('MyPageCtrl', { $scope: $scope});
}));

一些更多的解释:当你的应用真正运行时,$scope 会通过 angular 自动注入(inject)到你的 Controller 中。在您的测试中,您只是在隔离地测试您的 Controller ,因此您需要自己创建范围对象并伪造您想要的任何行为。使用 $rootScope().$new() 将为您提供 Angular 方法,如 $watch 或 $on,但您需要自己重新创建自己的方法。

关于javascript - Angular 单元测试 : Calling a method defined in another controller is throwing 'undefined' is not an error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886001/

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