如何在Angular单元测试中从另一个控制器的rootScope将方法添加到rootScope中

How to add a method into rootScope from the rootScope from another controller in an Angular unit test?

本文关键字:rootScope 方法 添加 控制器 另一个 Angular 单元测试      更新时间:2023-09-26

我正在单元测试一个函数,该函数从另一个控制器调用$rootScope方法。有没有办法将该函数添加到我要测试的控制器的$rootScope中?我使用的测试环境包括Jasmine、Karma、PhantomJS等。

如果你想在测试中手动添加方法,你可以在测试运行前使用Jasmine的beforeEach()来设置mock/implement方法,所以通过使用inject(),你可以传入$rootScope并设置你的方法

由于$rootScope在所有控制器之间共享,您可以直接在$rootScope对象中定义函数,请考虑将函数定义在app.run处理程序中,否则,您必须确保已加载控制器才能定义函数,下面的示例显示了这两种方法:

<div ng-app="myApp">
<div ng-controller="Ctrl1">
  <h1>Controller 1</h1>
  <button ng-click="myFunc()">Test $rootScope.myFunc()</button>
  <button ng-click="toBeDefniendinCtrl1()">Test $rootScope.toBeDefniendinCtrl1()</button>
</div>
<div ng-controller="Ctrl2">
   <h1>Controller 2</h1>
  <button ng-click="myFunc()">Test $rootScope.myFunc()</button>
  <button ng-click="toBeDefniendinCtrl1()">Test $rootScope.toBeDefniendinCtrl1()</button>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope){
  $rootScope.myFunc = function (){ alert("hi"); }
  $rootScope.toBeDefniendinCtrl1 = null;
})  
app.controller('Ctrl1', function($scope, $rootScope) {
  $rootScope.toBeDefniendinCtrl1 = function (){ alert("hello from Ctrl1"); }   
});
app.controller('Ctrl2', function($scope, $rootScope) {

});
</script>

请参阅以下位置的工作示例:http://jsbin.com/xiyozitage/edit?html,输出