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


Tengo una aplicación Angular/Laravel existente en la que Laravel actúa como una API para el frontend angular que sirve solo datos JSON. La página que carga la aplicación angular, index.php, está actualmente servida por Laravel. A partir de ahí, Angular se hace cargo.

Estoy teniendo un tiempo muy difícil tratando de empezar con Karma/Jasmine. Al ejecutar mis pruebas usando karma start o karma start karma.conf.js desde el directorio raíz de mi proyecto, obtengo el siguiente error:

ReferenceError: module is not defined

Completo salida:

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)

Sin embargo, el broswer chrome se inicia con lo siguiente:

introduzca la descripción de la imagen aquí

Mi archivo karma.conf.js es el siguiente:

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

Mi archivo package.json se muestra a continuación:

{
  "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();
    });
});

Cualquier ayuda sería grandemente apreciada.

Author: Raphael Rafatpanah, 2014-12-23

4 answers

Quizás esto ayude a alguien.

La solución, para mí, era asegurarme de que angular-mocks.js se cargara antes de mis pruebas. Si no está seguro, puede controlar el orden en karma.conf.js en la siguiente sección:

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

A continuación, para que mi prueba realmente cargue mi aplicación angular, tuve que hacer lo siguiente:

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

});

Y en su controlador,

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

    this.message = "Hello";

});

También, de otra manera:

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

});

Disfrute de las pruebas!

 74
Author: Raphael Rafatpanah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-23 18:30:58

El error significa que angular no pudo inyectar su módulo. La mayoría de las veces esto sucede debido a la falta de referencia a los archivos de script. En este caso, asegúrese de tener todo el archivo de script está definido en la configuración [files] de karma. Preste especial atención a las rutas porque si su carpeta de script tiene una estructura anidada, asegúrese de listar como tal. Por ejemplo:

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

Se puede enumerar como en karma.conf.js > archivos como:

Scripts/Controllers/**/*.js
 5
Author: Maksood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-10 06:15:26

Simplemente deje esto aquí para futuros buscadores.

Si está ejecutando pruebas unitarias angulares en el navegador directamente sin Karma (o en plunkr o jsfiddle ect...), Entonces puede ser que

<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 -->

La configuración de Mocha va ENTRE angular y angular-se burla

 4
Author: Fresheyeball,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-29 06:23:42

Me encontré con un mensaje similar y resultó que obtuve mi angular-mocks ruta de archivo incorrecta. Usé npm para instalar angular y angular-mocks, y especificé su ruta incorrectamente en mi Karma.conf.js así:

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

Debería especificar la ruta de angular-mocks.js como esta:

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

Error muy simple, pero podría llevar mucho tiempo localizarlo si acaba de comenzar con las pruebas unitarias de AngularJS y no sabía dónde buscar.

 0
Author: Charlie Guan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-06 02:59:29