I am unit testing a function that calls a $rootScope method from another controller. Is there a way to add that function to the $rootScope of the controller I am trying to test? I'm using a test environment that includes Jasmine, Karma, PhantomJS, etc.
如果要在测试中手动添加方法,则可以在运行测试之前使用Jasmine的beforeEach()设置模拟 /实现方法,因此可以使用inject()
传入$rootScope
并设置方法
Since $rootScope is shared across all your controllers, you could define your function directly in $rootScope object, consider putting the function definition in the app.run handler, otherwise, you have to make sure your controller is loaded for the function to be defined, the example below shows both methods:
<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>
see a working example at: http://jsbin.com/xiyozitage/edit?html,output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.