0

I've just started using Jasmine for testing an AngularJS app. I believe I'm doing all the imports on the SpecRunner but I get the error:

TypeError: $scope.$on is not a function

I'm using this in my controller as follows:

app.controller('asstCtrl', function($scope, $uibModal, $interval, $document) {
    $scope.$on('$includeContentLoaded', function() {        
        $scope.doStuff();          
    });
});

...

My SpecRunner test is looking like this:

describe('calculator', function(){
   beforeEach(module('asst'));
   it('basic', inject(function($controller) {
      var scope = {},
          ctrl = $controller('asstCtrl', {$scope:scope});
     expect(scope.x).toBe(1);
   }));
});

These are my imports:

  • public/js/jasmine-2.4.0/jasmine.js
  • public/js/jasmine-2.4.0/jasmine-html.js
  • public/js/jasmine-2.4.0/boot.js
  • public/js/jquery.min.js
  • public/js/angular.js public/js/angular-animate.min.js
  • public/js/angular-mocks.js
  • public/js/ui-bootstrap-tpls-0.14.2.min.js

The app runs fine and the test runs if I remove the $scope.$on section from my controller. I must be doing something wrong in the SpecRunner or something works differently when I inject the controller. Can anyone help me with this?

EDIT

Test ended up looking like this:

describe('calculator', function(){
   beforeEach(module('asst'));
   var rootScope;
   beforeEach(inject(function($rootScope) {
     rootScope = $rootScope;
   }));
   it('basic', inject(function($controller) {
      var scope = rootScope.$new(),
          ctrl = $controller('asstCtrl', {$scope:scope});
     expect(scope.x).toBe(1);
   }));
});
Craveiro
  • 503
  • 5
  • 15

1 Answers1

0

You are creating an object and injecting that as the controller“s scope. There will not be a $on method on that object.

Instead inject $rootScope and use the method $new to create a scope:

var scope = $rootScope.$new(),
    ctrl = $controller('asstCtrl', { $scope: scope });
tasseKATT
  • 38,470
  • 8
  • 84
  • 65