如何使用RequireJS测试AngularJS控制器?

时间:2013-07-30 19:07:41

标签: angularjs requirejs jasmine karma-runner

这是我的Jasmine规范,

define(['app', 'angular', 'angularResource', 'angularMocks'], function() {
describe('App module tests', function(){
    var module, $rootScope, scope, AppCtrl;
    beforeEach(function () {
        module = angular.module("MyApp");
        inject(function($rootScope, $controller){
            // The injector unwraps the underscores (_) from around the parameter names when matching
            scope = $rootScope.$new();
            AppCtrl = $controller('AppCtrl', {$scope: scope});
        });
    });
    });
});

在我的app.js中,我有..

var MyApp = angular.module('MyApp');
MyApp.controller('AppCtrl', ['$rootScope', function($rootScope){
// controller code here
}]);

当我运行单元测试时,我得到以下错误,

错误:参数'AppCtrl'不是函数,未定义

另外,这是我的test-main.js,

var tests = Object.keys(window.__karma__.files).filter(function (file) {
    return (/Spec\.js$/).test(file);
});
requirejs.config({
    // Karma serves files from '/base'
    baseUrl: '/base/src',
    paths: {
        'angular': 'libs/angular',
        'angularResource': 'libs/angular-resource',
        'angularMocks': 'libs/angular-mocks',
        'app': 'app/app'
    },
    // ask Require.js to load these files (all our tests)
    deps: tests,
    // start test run, once Require.js is done
    callback: window.__karma__.start
});

我的业力配置,

// list of files / patterns to load in the browser
files = [
    JASMINE,
    JASMINE_ADAPTER,
    REQUIRE,
    REQUIRE_ADAPTER,
    'src/libs/angular.js',
    'src/libs/angular-resource.js',
    'src/libs/angular-mocks.js',
    {pattern: 'src/app/*.js', included: false},
    {pattern: 'src/app/**/*.js', included: false},
    {pattern: 'test/**/*Spec.js', included: false},
    'test/test-main.js'
];

1 个答案:

答案 0 :(得分:2)

试试这个。我认为你需要摆脱包装inject()的功能。

define(['app', 'angular', 'angularResource', 'angularMocks'], function () {
    describe('App module tests', function () {
        var module, $rootScope, scope, AppCtrl;
        beforeEach(angular.module("MyApp"));

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

Editied:

我认为你需要ANGULAR_SCENARIO_ADAPTER来处理业力。