ReferenceError: module is not defined – Karma/Jasmine configuration with Angular/Laravel app

All we need is an easy explanation of the problem, so here it is.

I have an existing Angular/Laravel app in which Laravel acts as an API to the angular frontend serving only JSON data. The page that loads the angular app, index.php, is currently served by Laravel. From there, Angular takes over.

I’m have a very difficult time trying to get started with Karma/Jasmine. When running my tests using karma start or karma start karma.conf.js from the root directory of my project, I get the following error:

ReferenceError: module is not defined

Full output:

INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [watcher]: Pattern "/Users/raph/coding/webroot/digitalocean/rugapp/public/rugapp/*.js" does not match any file.
INFO [Chrome 39.0.2171 (Mac OS X 10.9.5)]: Connected on socket 3OCUMp_xhrGtlGHwiosO with id 7897120
Chrome 39.0.2171 (Mac OS X 10.9.5) hello world encountered a declaration exception FAILED
    ReferenceError: module is not defined
        at Suite.<anonymous> (/Users/raph/coding/webroot/digitalocean/rugapp/tests/js/test.js:3:16)
        at jasmineInterface.describe (/Users/raph/coding/webroot/digitalocean/rugapp/node_modules/karma-jasmine/lib/boot.js:59:18)
        at /Users/raph/coding/webroot/digitalocean/rugapp/tests/js/test.js:1:1
Chrome 39.0.2171 (Mac OS X 10.9.5): Executed 2 of 2 (1 FAILED) (0.005 secs / 0.003 secs)

However, the chrome broswer does launch with the following displayed:

enter image description here

My karma.conf.js file is as follows:

// Karma configuration
// Generated on Mon Dec 22 2014 18:13:09 GMT-0500 (EST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: 'public/rugapp/',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      '*.html',
      '**/*.js',
      '../../tests/js/test.js',
      '../../tests/js/angular/angular-mocks.js'
    ],


    // list of files to exclude
    exclude: [

    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


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


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


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

My package.json file is shown below:

{
  "devDependencies": {
    "gulp": "^3.8.8",
    "karma": "^0.12.28",
    "karma-chrome-launcher": "^0.1.7",
    "karma-jasmine": "^0.3.2",
    "laravel-elixir": "*"
  }
}

test.js

describe("hello world", function() {
    var CreateInvoiceController;
    beforeEach(module("MobileAngularUiExamples"));
    beforeEach(inject(function($controller) {
        CreateInvoiceController = $controller("CreateInvoiceController");
    }));

    describe("CreateInvoiceController", function() {
        it("Should say hello", function() {
            expect(CreateInvoiceController.message).toBe("Hello");
        });
    });
});

describe("true", function() {
    it("Should be true", function() {
        expect(true).toBeTruthy();
    });
});

Any help would be greatly appreciated.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Perhaps this will help someone.

The solution, for me, was to make sure angular-mocks.js was loaded before my tests. If you’re not sure, you control the order in karma.conf.js under the following section:

// list of files / patterns to load in the browser
files: [
// include files / patterns here

Next, to get my test to actually load my angular app, I had to do the following:

describe("hello world", function() {
    var $rootScope;
    var $controller;
    beforeEach(module("YourAppNameHere"));
    beforeEach(inject(function($injector) {

        $rootScope = $injector.get('$rootScope');
        $controller = $injector.get('$controller');
        $scope = $rootScope.$new();

    }));
    beforeEach(inject(function($controller) {
        YourControllerHere = $controller("YourControllerHere");

    }));

    it("Should say hello", function() {
        expect(YourControllerHere.message).toBe("Hello");
    });

});

And in your controller,

app.controller('YourControllerHere', function() {

    this.message = "Hello";

});

Also, another way:

describe("YourControllerHere", function() {
    var $scope;
    var controller;

    beforeEach(function() {

        module("YourAppNameHere");

        inject(function(_$rootScope_, $controller) {

            $scope = _$rootScope_.$new();
            controller = $controller("YourControllerHere", {$scope: $scope});

        });

    });

    it("Should say hello", function() {
        expect(controller.message).toBe("Hello");
    });

});

Enjoy testing!

Method 2

The error means angular was not able to inject your module. Most of the time this happens because of missing reference to script files. In this case, make sure to have all your script file is defined under [files] configuration of karma. Pay special attention to paths because if your script folder has nested structure, make sure to list as such. For example:

Scripts/Controllers/One/1.js 
Scripts/Controllers/One/2.js 

can be listed as in karma.conf.js>files as :

Scripts/Controllers/**/*.js

Method 3

Just leave this here for future searchers.

If you are running angular unit tests in the browser directly without Karma (or in plunkr or jsfiddle ect…) Then it may be that

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-route.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-cookies.js"></script> 

    <!-- The Mocha Setup goes BETWEEN angular and angular-mocks -->
    <script>
      mocha.setup({
        "ui": "bdd",
        "reporter": "html"
      });
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular-mocks.js"></script>
    <script src="myApp.js"></script>
    <script src="myTest.js"></script> <!-- test is last -->

The Mocha Setup goes BETWEEN angular and angular-mocks

Method 4

I encountered a similar message and turned out I got my angular-mocks file path wrong. I used npm to install angular and angular-mocks, and I specified their path wrongly in my Karma.conf.js like this:

files: [
    'node_modules/angular/angular.js',
    'node_modules/angular/angular-mocks.js',
    'scripts/*.js',
    'tests/*.js'
],

I should specify the path of angular-mocks.js as this:

'node_modules/angular-mocks/angular-mocks.js'

Very simple error, but could be time-consuming to locate if you just started with AngularJS unit testing and didn’t know where to look.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply