【问题标题】:Controller undeclared in Jasmine testJasmine 测试中未声明控制器
【发布时间】:2014-04-15 10:24:15
【问题描述】:

我有以下 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

此代码最终出错(业力/茉莉花输出):

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

可能是什么原因?

【问题讨论】:

  • 您确定要注入您的模块吗? beforeEach(function() { module('myModule'); });
  • @c0bra 你的意思是有控制器 ProjectConfigurationCtrl 的模块?
  • 错误是关于controllerToTest,不是实际控制人。您必须在beforeEach 之后为controllerToTest 分配了一个非函数值。

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


【解决方案1】:

c0bra和Ye Lio在这方面都有所长。

c0bra 是正确的,因为您没有调用 karma/jasmine 辅助方法“模块”来包含包含“ProjectConfigurationCtrl”的模块。

您需要添加如下内容:

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

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

错误:[ng:areq] 参数 'ProjectConfigurationCtrl' 不是函数,未定义

但是,您看到的错误“TypeError: controllerToTest is not a function”表明 controllerToTest 在其他地方被设置为不是函数的东西。

如果这些都不能解决您的问题,请发布带有上述建议的新的、完整的测试版本。

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多