Can't create controller instance for Karma Angular tests

So I've seen a few similar questions asked on SO about this but I've had no luck with each of them. My Karma controller test is unable to create an instance of the controller it is testing.

I get this error when calling the createController method:

Error: [ng:areq] Argument 'ActivationController' is not a function, got undefined

Controller test:

    'use strict';

    fdescribe('Controller Tests', function() {

        describe('ActivationController', function() {

            beforeEach(module('myApp'));

            var $scope, $httpBackend, $q; // actual implementations
            var MockAuth, MockStateParams; // mocks
            var createController; // local utility function

            beforeEach(function() {
                var $injector = angular.injector(['ng']);

                $q = $injector.get('$q');
                $scope = $injector.get('$rootScope').$new();
                $httpBackend = $injector.get('$httpBackend');
                MockAuth = jasmine.createSpyObj('MockAuth', ['activateAccount']);
                MockStateParams = jasmine.createSpy('MockStateParams');
                MockStateParams.key = 'ABC123';

                var locals = {
                    '$scope': $scope,
                    '$stateParams': MockStateParams,
                    'Auth': MockAuth
                };
                createController = function() {
                    angular.injector(['ng']).get('$controller')('ActivationController as vm', locals);
                };
            });

            it('calls Auth.activateAccount with the key from stateParams', function() {
                // given
                MockAuth.activateAccount.and.returnValue($q.resolve());
                // when
                $scope.$apply(createController);
                // then
                expect(MockAuth.activateAccount).toHaveBeenCalledWith({
                    key: 'ABC123'
                });
            });
        });
    });

Controller:

    (function() {
        'use strict';

        angular
            .module('myApp')
            .controller('ActivationController', ActivationController);

        ActivationController.$inject = ['$stateParams', 'Auth', 'LoginService'];

        function ActivationController ($stateParams, Auth, LoginService) {
            var vm = this;

            Auth.activateAccount({key: $stateParams.key}).then(function () {
                vm.error = null;
                vm.success = 'OK';
            }).catch(function () {
                vm.success = null;
                vm.error = 'ERROR';
            });

            vm.login = LoginService.open;
        }
    })();

Karma config:

    // Karma configuration
    // http://karma-runner.github.io/0.13/config/configuration-file.html

    // var sourcePreprocessors = ['coverage'];
    var sourcePreprocessors = [];

    function isDebug() {
        return process.argv.indexOf('--debug') >= 0;
    }

    if (isDebug()) {
        // Disable JS minification if Karma is run with debug option.
        sourcePreprocessors = [];
    }

    module.exports = function (config) {
        config.set({
            // base path, that will be used to resolve files and exclude
            basePath: 'src/test/javascript/'.replace(/[^/]+/g,'..'),

            // testing framework to use (jasmine/mocha/qunit/...)
            frameworks: ['jasmine'],

            // list of files / patterns to load in the browser
            files: [
                'src/main/webapp/ext/tinymce/tinymce.min.js',
                // bower:js
                'src/main/webapp/bower_components/jquery/dist/jquery.js',
                'src/main/webapp/bower_components/messageformat/messageformat.js',
                'src/main/webapp/bower_components/json3/lib/json3.js',
                'src/main/webapp/bower_components/sockjs-client/dist/sockjs.js',
                'src/main/webapp/bower_components/stomp-websocket/lib/stomp.min.js',
                'src/main/webapp/bower_components/moment/moment.js',
                'src/main/webapp/bower_components/intl-tel-input/build/js/intlTelInput.min.js',
                'src/main/webapp/bower_components/intl-tel-input/lib/libphonenumber/build/utils.js',
                'src/main/webapp/bower_components/matchmedia/matchMedia.js',
                'src/main/webapp/bower_components/blob-polyfill/Blob.js',
                'src/main/webapp/bower_components/file-saver.js/FileSaver.js',
                'src/main/webapp/bower_components/moment-timezone/builds/moment-timezone-with-data.js',
                'src/main/webapp/bower_components/Case/dist/Case.js',
                'src/main/webapp/bower_components/js-quantities/build/quantities.js',
                'src/main/webapp/bower_components/angular/angular.js',
                'src/main/webapp/bower_components/angular-aria/angular-aria.js',
                'src/main/webapp/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
                'src/main/webapp/bower_components/angular-cache-buster/angular-cache-buster.js',
                'src/main/webapp/bower_components/angular-cookies/angular-cookies.js',
                'src/main/webapp/bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js',
                'src/main/webapp/bower_components/ngstorage/ngStorage.js',
                'src/main/webapp/bower_components/angular-loading-bar/build/loading-bar.js',
                'src/main/webapp/bower_components/angular-resource/angular-resource.js',
                'src/main/webapp/bower_components/angular-sanitize/angular-sanitize.js',
                'src/main/webapp/bower_components/angular-translate/angular-translate.js',
                'src/main/webapp/bower_components/angular-translate-interpolation-messageformat/angular-translate-interpolation-messageformat.js',
                'src/main/webapp/bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js',
                'src/main/webapp/bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js',
                'src/main/webapp/bower_components/angular-ui-router/release/angular-ui-router.js',
                'src/main/webapp/bower_components/bootstrap-ui-datetime-picker/dist/datetime-picker.js',
                'src/main/webapp/bower_components/ng-file-upload/ng-file-upload.js',
                'src/main/webapp/bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
                'src/main/webapp/bower_components/angular-recaptcha/release/angular-recaptcha.js',
                'src/main/webapp/bower_components/angular-ui-select/dist/select.js',
                'src/main/webapp/bower_components/fullcalendar/dist/fullcalendar.js',
                'src/main/webapp/bower_components/international-phone-number/releases/international-phone-number.js',
                'src/main/webapp/bower_components/angular-animate/angular-animate.js',
                'src/main/webapp/bower_components/angular-messages/angular-messages.js',
                'src/main/webapp/bower_components/angular-input-masks/angular-input-masks-standalone.js',
                'src/main/webapp/bower_components/ngSticky/lib/sticky.js',
                'src/main/webapp/bower_components/angular-ui-mask/dist/mask.js',
                'src/main/webapp/bower_components/angular-file-saver/dist/angular-file-saver.bundle.js',
                'src/main/webapp/bower_components/angular-drag-and-drop-lists/angular-drag-and-drop-lists.js',
                'src/main/webapp/bower_components/angular-ui-tinymce/src/tinymce.js',
                'src/main/webapp/bower_components/angular-fcsa-number/src/fcsaNumber.js',
                'src/main/webapp/bower_components/angular-moment/angular-moment.js',
                'src/main/webapp/bower_components/angular-xeditable/dist/js/xeditable.js',
                'src/main/webapp/bower_components/ngmap/build/scripts/ng-map.js',
                'src/main/webapp/bower_components/ng-idle/angular-idle.js',
                'src/main/webapp/bower_components/angular-mocks/angular-mocks.js',
                'src/main/webapp/bower_components/angular-ui-calendar/src/calendar.js',
                'src/main/webapp/bower_components/angular-material/angular-material.js',
                'src/main/webapp/bower_components/lf-ng-md-file-input/dist/lf-ng-md-file-input.js',
                // endbower
                'src/main/webapp/app/app.module.js',
                'src/main/webapp/app/app.state.js',
                'src/main/webapp/app/app.constants.js',
                'src/main/webapp/app/**/*.+(js|html)',
                'src/test/javascript/spec/helpers/module.js',
                'src/test/javascript/spec/helpers/httpBackend.js',
                'src/test/javascript/spec/app/**/*.js'
            ],


            // list of files / patterns to exclude
            exclude: ['src/test/javascript/e2e/**'],

            preprocessors: {
                './**/*.js': sourcePreprocessors
            },

            reporters: ['coverage', 'progress'],

            coverageReporter: {
                dir: 'build/test-results/coverage',
                reporters: [
                    {type: 'lcov', subdir: 'report-lcov'}
                ]
            },

            // web server port
            port: 9876,

            // level of logging
            // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
            logLevel: config.LOG_DEBUG,

            // enable / disable watching file and executing tests whenever any file changes
            autoWatch: false,

            // Start these browsers, currently available:
            // - Chrome
            // - ChromeCanary
            // - Firefox
            // - Opera
            // - Safari (only Mac)
            // - PhantomJS
            // - IE (only Windows)
            browsers: ['PhantomJS'],

            // Continuous Integration mode
            // if true, it capture browsers, run tests and exit
            singleRun: false,

            // to avoid DISCONNECTED messages when connecting to slow virtual machines
            browserDisconnectTimeout : 10000, // default 2000
            browserDisconnectTolerance : 1, // default 0
            browserNoActivityTimeout : 4*60*1000 //default 10000
        });
    };

If it helps, this test was generated by Jhipster, but I had to alter the injection to use factory injection instead of service injection as I was having an issue with the angular dependencies not being injected properly.

Answers:

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.