Joseph Goulet
Joseph Goulet

Reputation: 1

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

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.

Upvotes: 0

Views: 298

Answers (2)

Shadi Shaaban
Shadi Shaaban

Reputation: 1720

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

Upvotes: 0

Chris Brown
Chris Brown

Reputation: 4635

If you want to manually add the method in the test you can use Jasmine's beforeEach() to set up mocks/implement methods before your tests run, so by using inject() you can pass in $rootScope and set your method

Upvotes: 0

Related Questions