angularjs - How to unit test Angular controller with $scope.$on? -
i have controller event listener in angular app, defined follows.
angular.module('test').controller('testctrl', function($rootscope, $scope, testservice) { [...] $scope.$on("myevent", function(args, value) { testservice.dostuff(value); }); }); this works in app itself. however, when try unit test functionality of controller (using jasmine , karma), each test method throws following error:
typeerror: $scope.$on not function in [...]/testcontroller.js i create controller in test methods follows.
it('does stuff', inject(function($rootscope, $controller, testservice) { var scope = $rootscope.$new; $controller('testctrl', { $scope : scope }); [...] })); i can around problem changing controller use rootscope instead:
$rootscope.$on(...) but of course app doesn't work anymore expected. can rid of error introducing $on method in test code:
var scope = $rootscope.$new; scope.$on = function() {}; but mocking listener kind of defeats purpose of testing real code.
why doesn't test code find the $on method of the scope? (but finds on rootscope, still...)
there must fundamental i'm missing here haven't been able figure out after lots of googling , reading angular source code.
$rootscope.$new function. need invoke ($rootscope.$new()):
it('does stuff', inject(function($rootscope, $controller, testservice) { var scope = $rootscope.$new(); $controller('testctrl', { $scope : scope }); [...] })); example plunk: http://plnkr.co/edit/t1x62msmoqdknitgzcp9?p=preview
Comments
Post a Comment