Controller undeclared in Jasmine test

情到浓时终转凉″ 提交于 2019-12-10 23:38:21

问题


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

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