Javascript ReferenceError:未定义模块 - 使用 Angular/Laravel 应用程序配置 Karma/Jasmine

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27622382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:24:36  来源:igfitidea点击:

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

javascriptangularjskarma-runnerkarma-jasmine

提问by Raphael Rafatpanah

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.

我有一个现有的 Angular/Laravel 应用程序,其中 Laravel 充当仅提供 JSON 数据的 Angular 前端的 API。加载index.phpAngular应用程序的页面目前由 Laravel 提供服务。从那里,Angular 接管了。

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

我很难开始使用 Karma/Jasmine。使用karma startkarma start karma.conf.js从我的项目的根目录运行我的测试时,我收到以下错误:

ReferenceError: module is not defined

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:

但是,Chrome 浏览器确实启动并显示以下内容:

enter image description here

在此处输入图片说明

My karma.conf.jsfile is as follows:

我的karma.conf.js文件如下:

// 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.jsonfile is shown below:

我的package.json文件如下所示:

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

test.js

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

任何帮助将大大赞赏。

回答by Raphael Rafatpanah

Perhaps this will help someone.

也许这会帮助某人。

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

对我来说,解决方案是确保angular-mocks.js在我的测试之前加载。如果您不确定,您可以karma.conf.js在以下部分控制顺序:

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

接下来,为了让我的测试真正加载我的 angular 应用程序,我必须执行以下操作:

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!

享受测试!

回答by Maksood

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:

该错误意味着 angular 无法注入您的模块。大多数情况下,这是因为缺少对脚本文件的引用。在这种情况下,请确保在 karma 的 [files] 配置下定义所有脚本文件。特别注意路径,因为如果您的脚本文件夹具有嵌套结构,请确保按此类列出。例如:

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

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

可以在 karma.conf.js>files 中列为:

Scripts/Controllers/**/*.js

回答by Fresheyeball

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

如果您在没有 Karma(或在 plunkr 或 jsfiddle 等...)的情况下直接在浏览器中运行 Angular 单元测试,那么可能是

<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

Mocha 设置介于 angular 和 angular-mocks 之间

回答by Charlie Guan

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

我遇到了类似的消息,结果发现我的angular-mocks文件路径错误。我使用 npm 来安装angularand angular-mocks,并且我错误地指定了它们的路径,Karma.conf.js如下所示:

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

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

我应该指定这样的路径angular-mocks.js

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

非常简单的错误,但如果您刚开始使用 AngularJS 单元测试并且不知道在哪里查找,则可能会很耗时。