Chandra
Chandra

Reputation: 505

How do I test AngularJS controllers using RequireJS?

Here's my Jasmine spec,

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});
        });
    });
    });
});

In my app.js, I have..

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

When I run the unit test, I get below error,

Error: Argument 'AppCtrl' is not a function, got undefined

Also, here's my 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
});

And my karma configuration,

// 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'
];

Upvotes: 0

Views: 3512

Answers (1)

zs2020
zs2020

Reputation: 54514

Try this. I think you need to get rid off the function wrapping the 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:

I think you need ANGULAR_SCENARIO_ADAPTER to work with karma.

Upvotes: 2

Related Questions