问题
I have a following code for Jasmine testing. ProjectConfigurationCtrl is the name of controller I am trying to test.
describe('Unit test: ProjectConfiguration controller', function() {
var scope, routeParams, infraService, controllerToTest;
// some stuff declaration skipped...
beforeEach(inject(function($injector) { // get all dependences
routeParams = $injector.get('$routeParams');
infraService = $injector.get('InfraService');
$rootScope = $injector.get('$rootScope');
scope = $rootScope.$new();
scope.projectData = fakedDto;
var $controller = $injector.get('$controller');
controllerToTest = function() {
return $controller('ProjectConfigurationCtrl', { //
'$scope': scope
});
};
}));
// ...
it('saves new project successfully', function() {
var controller = controllerToTest();
// here, I try to call test function in and check results...
scope.clickUpdate(fakedDto); // <-- controller defines this function in given scope, so I hope it runs like this in test.
});
}); // describe block ends
this code ends up in error (karma/jasmine output):
minErr/<@C:/src/ClientApp/client/bower_components/angular/angular.js:78
loadModules/<@C:/src/ClientApp/client/bower_components/angular/angular.js:3703
forEach@C:/src/ClientApp/client/bower_components/angular/angular.js:322
loadModules@C:/src/ClientApp/client/bower_components/angular/angular.js:3668
createInjector@C:/src/ClientApp/client/bower_components/angular/angular.js:3608
workFn@C:/src/ClientApp/client/bower_components/angular-mocks/angular-mocks.js:2144
TypeError: controllerToTest is not a function in C:/src/ClientApp/tests/unit/controllers/projectconfigcontroller.test.js (line 85)
@C:/src/ClientApp/tests/unit/controllers/projectconfigcontroller.test.js:85
what could be the reason?
回答1:
c0bra and Ye Lio both have good points here.
c0bra is right in that you have not called the karma/jasmine helper method 'module' to include the module that contains 'ProjectConfigurationCtrl'.
You need to add something like the following:
beforeEach( module( 'module.containing.ProjectConfigurationCtrl' ) );
If you don't do this you will get an error like the following when running the script above:
Error: [ng:areq] Argument 'ProjectConfigurationCtrl' is not a function, got undefined
However, the error you are seeing "TypeError: controllerToTest is not a function" indicated that somehow controllerToTest is getting set somewhere else to something that is not a function.
If none of this fixes your problem please post a new, complete version of your test w/ the above suggestions in place.
来源:https://stackoverflow.com/questions/22331970/controller-undeclared-in-jasmine-test