控制器未在Jasmine测试中声明

时间:2014-03-11 17:19:09

标签: angularjs unit-testing testing jasmine karma-runner

我有以下代码用于Jasmine测试。 ProjectConfigurationCtrl是我试图测试的控制器的名称。

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

此代码最终出错(karma / jasmine输出):

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

可能是什么原因?

1 个答案:

答案 0 :(得分:1)

c0bra和Ye Lio在这里都有好处。

c0bra是正确的,因为你没有调用业力/茉莉花辅助方法&#39;模块&#39;包含包含&#39; ProjectConfigurationCtrl&#39;的模块。

您需要添加以下内容:

beforeEach( module( 'module.containing.ProjectConfigurationCtrl' ) );

如果您不这样做,在运行上述脚本时会出现如下错误:

错误:[ng:areq] Argument&#39; ProjectConfigurationCtrl&#39;不是一个功能,未定义

但是,您看到的错误&#34; TypeError:controllerToTest不是函数&#34;表示不知何故,controllerToTest正在其他地方被设置为不是函数的东西。

如果这些都无法解决您的问题,请发布一个新的完整版本的测试,并附上上述建议。