mercredi 25 février 2015

Testing Angular with parent controller method call

I'm trying to write unit-tests for an Angular application for the first time. Currently i'm having some problems running the tests. Running the application normally works fine, it doesn't give any errors. However, when running the tests using Karma and Jasmine i'm getting the following error:



TypeError: 'undefined' is not a function (evaluating '$scope.addActiveClassToMenuButton('menuButtonHome')')


I'm using the ui.router module. Not sure if that matters.


Parent controller


Parent controller contains the following method:



angular.module('testApp')
.controller('ParentCtrl', function ($scope, $resource) {

$scope.addActiveClassToMenuButton = function(buttonId) {
//Some code
}

}


Child controller


Child controller calls the parents method like this:



angular.module('testApp')
.controller('ChildCtrl', function ($scope, $resource) {

$scope.addActiveClassToMenuButton('menuButtonHome');

}


Child controller test file


The test file that fails:



describe('Child controller tests. ', function () {
beforeEach(module('testApp'));

var ChildCtrl, scope;

beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ChildCtrl = $controller('ChildCtrl', {
$scope: scope
});
}));

it('simple false test', function () {
expect(false).toBe(false);
});
});


Even though i'm not using the scope in the test yet, all tests fail because the code can't find the parents method.


Aucun commentaire:

Enregistrer un commentaire