Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to unit test Angular controller with $scope.$on?
    text
    copied!<p>I have a controller with an event listener in my Angular app, defined as follows.</p> <pre><code> angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) { [...] $scope.$on("myEvent", function(args, value) { testService.doStuff(value); }); }); </code></pre> <p>This works perfectly in the app itself. However, when I try to unit test the functionality of the controller (using <em>Jasmine</em> and <em>Karma</em>), each test method throws the following error:</p> <pre><code> TypeError: $scope.$on is not a function in [...]/testController.js </code></pre> <p>I create the controller in my test methods as follows.</p> <pre><code> it('does stuff', inject(function($rootScope, $controller, testService) { var scope = $rootScope.$new; $controller('TestCtrl', { $scope : scope }); [...] })); </code></pre> <p>I can get around the problem by changing my controller to use <code>rootScope</code> instead:</p> <pre><code> $rootScope.$on(...) </code></pre> <p>but then of course the app doesn't work anymore as expected. I can also get rid of the error by introducing the <code>$on</code> method in my test code:</p> <pre><code> var scope = $rootScope.$new; scope.$on = function() {}; </code></pre> <p>but mocking the listener like this kind of defeats the purpose of testing my real code.</p> <p><strong>Why doesn't the test code find the</strong> <code>$on</code> <strong>method of the</strong> <code>scope</code><strong>?</strong> (But finds it on <code>rootScope</code>, still...)</p> <p>There must be something fundamental that I'm missing here but I haven't been able to figure it out even after lots of googling and reading the Angular source code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload