$scope.$on not working in Jasmine SpecRunner

核能气质少年 提交于 2019-12-12 05:27:12

问题


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);
   }));
});

回答1:


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 });


来源:https://stackoverflow.com/questions/34654889/scope-on-not-working-in-jasmine-specrunner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!