Reputation: 127
I'm using Jasmine/Karma to test Angularjs code and I'm brand new to Jasmine. I've got a basic test using expect(true).toEqual(true)
which works, so it seems like the set up is okay. Once I try to test something that actually uses a controller, I get the following:
TypeError: undefined is not a function (evaluating '$scope.$on('myEvent', function(event,data)
I have several $scope.$on methods and it doesn't matter what order they are in, it complains about the first one. Here is an excerpt of how the controller is set up:
angular.module('myProject.dataType')
.controller('DataTypeController', ['$scope', '$state', '$rootScope', function($scope, $state, $rootScope) {
$scope.dataTypeId="";
...other stuff...
$scope.$on('myEvent', function(event, data) {
$scope.dataTypeId = "";
});
}]);
Here is my spec file:
describe("Data Type Controller', function() {
beforeEach(module('myProject.dataType') );
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
describe('Create type', function() {
it('basic test', function() {
var $scope = {};
var controller = $controller('DataTypeController', {'$scope': $scope});
expect(true).toEqual(true);
});
});
});
Note that the actual code (not Jasmine) works just fine. If I comment out the "var controller
..." line, the test passes. I'm not actually trying to invoke anything at this point, so I'm not sure why it is hitting the $scope.$on
, let alone failing on it. My best guess is that there's something wrong with the way I have the scope set up in the spec file.
I have checked file versions (based on responses to similar questions) and did my best to make sure there are no typos or fat fingers involved. Any help is greatly appreciated.
Upvotes: 0
Views: 154
Reputation: 185
I believe you need to inject scope as well into your beforeEach fn instead of defining it as an empty object. Right now your $scope literally is an empty object so the method '$on' doesn't exist in the context of the test.
Use:
beforeEach(inject(function(_$controller_, _$rootScope_) {
$controller = _$controller_;
$scope = _$rootScope_.$new();
}));
Upvotes: 2