Nice programing

ReferenceError : 모듈이 정의되지 않았습니다-Angular / Laravel 앱을 사용한 Karma / Jasmine 구성

nicepro 2021. 1. 7. 21:20
반응형

ReferenceError : 모듈이 정의되지 않았습니다-Angular / Laravel 앱을 사용한 Karma / Jasmine 구성


Laravel이 JSON 데이터 만 제공하는 각도 프런트 엔드에 대한 API 역할을하는 기존 Angular / Laravel 앱이 있습니다. Angular 앱을로드하는 페이지 index.php는 현재 Laravel에서 제공합니다. 거기에서 Angular가 인수합니다.

Karma / Jasmine을 시작하는 데 매우 어려움을 겪고 있습니다. 내 프로젝트의 루트 디렉터리를 사용 karma start하거나 사용하여 테스트를 실행할 때 karma start karma.conf.js다음 오류가 발생합니다.

ReferenceError: module is not defined

전체 출력 :

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)

그러나 크롬 브라우저는 다음과 같이 실행됩니다.

여기에 이미지 설명 입력

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

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

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

어떤 도움이라도 대단히 감사하겠습니다.


아마도 이것은 누군가를 도울 것입니다.

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!


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

Just leave this here for future searchers.

Karma없이 (또는 plunkr 또는 jsfiddle 등에서 ...) 브라우저에서 각도 단위 테스트를 직접 실행하는 경우

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

Mocha 설정은 각도와 각도 목 사이로 이동합니다.


비슷한 메시지가 나타 났고 angular-mocks파일 경로가 잘못되었습니다. npm을 사용하여 설치 angular하고 다음과 같이 angular-mocks경로를 잘못 지정했습니다 Karma.conf.js.

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

다음과 angular-mocks.js같이 경로를 지정해야 합니다.

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

매우 간단한 오류이지만 AngularJS 단위 테스트를 막 시작했고 어디를 찾아야할지 모르는 경우 찾는 데 시간이 오래 걸릴 수 있습니다.

참조 URL : https://stackoverflow.com/questions/27622382/referenceerror-module-is-not-defined-karma-jasmine-configuration-with-angular

반응형