Возникла ошибка в afterAll ReferenceError: модуль не определен, ошибка теста Karma/Jasmine в nodejs

Я пытаюсь написать тесты для простого приложения m nodejs с кармой и жасмином в качестве основы. Я использую покрытие кармы для препроцессора. Вот структура проекта: введите здесь описание изображения

package.json

{
  "name": "tests",
  "version": "1.0.0",
  "description": "tests with karma in jasmine framework",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "karma start karma.conf.js"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "jasmine-core": "^3.4.0",
    "karma": "^4.2.0",
    "karma-chrome-launcher": "^3.1.0",
    "karma-coverage": "^1.1.2",
    "karma-jasmine": "^2.0.1"
  }
}

karma.conf.js

// Karma configuration
// Generated on Sat Aug 17 2019 09:37:53 GMT+0500 (Uzbekistan Standard Time)

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

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


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


        // list of files / patterns to load in the browser
        files: [
            'js/*.js',
            'test/*.test.js'
        ],


        // list of files / patterns to exclude
        exclude: [],


        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'test/*.test.js': ['coverage']
        },


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


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

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        // optionally, configure the reporter
        coverageReporter: {
            type: 'html',
            dir: 'coverage/'
        }
    })
}

Всякий раз, когда я запускаю npm test, я получаю следующую ошибку:

введите здесь описание изображения

custom-lodash.js

class CustomLodash {

    compact(array) {
        let newArray = [];
        for (let i = 0; i < array.length; i++) {
            if (!array[i] || array[i] === undefined || array[i] === null) {
                continue;
            }

            this.push(array[i])(newArray);
        }
        return newArray;
    }


}

let _ = new CustomLodash;

module.exports = {
    compact: _.compact
};

custom-lodash.test.js

describe("CustomLodash", function () {

    let utils;
    //This will be called before running each spec
    beforeEach(function () {
        console.log('before each');
        utils = new CustomLodash();
    });


    describe("when calc is used to peform basic math operations", function () {
        it("creates an array with all falsey values removed", function () {
            // expect(utils.compact([0, 1, false, 2, '', 3])).toBe([1, 2, 3]);
            let compact = utils.compact([0, 1, false, 2, '', 3]);
            console.log('before each in it is: ', compact);
            expect(compact).toEqual([1, 2, 3]);
           //console.log('is defined ', expect(compact).toEqual([1, 2, 3]));
        });
    })


});

Как видите, console.log выдает результат, что означает, что файл читается. Но когда я вызываю toBe() или toEqual(), я вижу, что вывод не определен (проверил это и в console.log). Любая помощь действительно оценивается. Я искал много ответов и реальных вопросов, но не могу исправить этот.


person Nodirabegimxonoyim    schedule 17.08.2019    source источник


Ответы (1)


Хочу поделиться своим решением этого случая.

Добавление браузера сработало для меня. Кроме того, я добавил watchify для просмотра файлов для инкрементной компиляции.

Browserify был создан, чтобы сделать ваш код Node в браузере. На сегодняшний день он поддерживает только разновидность общих узлов (включая поддержку JSON) и предоставляет встроенные прокладки для многих основных модулей узла. Все остальное в другом пакете.

Вот как выглядит мой package.json после добавления пакетов для запуска моего кода ES6 как в браузере, так и в Node:

"dependencies": {
    "browserify": "^16.2.3",
    "jasmine-core": "^3.2.1",
    "karma": "^4.2.0",
    "karma-chrome-launcher": "^3.1.0",
    "karma-browserify": "^5.3.0",
    "karma-commonjs": "^1.0.0",
    "karma-coverage": "^1.1.2",
    "karma-jasmine": "^2.0.1"
    "watchify": "^3.11.0"
  }

Не забудьте добавить браузер в конфигурацию karma.config.js следующим образом:

  • добавьте его в свой список фреймворков

  • добавьте его в свой список препроцессоров.

Пример:

preprocessors: {
      'src/**/*.js': ['coverage'],
      'js/**/*.js': ['browserify'],
      'test/**/*.[sS]pec.js': ['browserify']
    }

Можно решить проблему такого рода с помощью ES6, создав webpack, но поскольку browserify с большей вероятностью будет работать с минимальной конфигурацией, я решил использовать его в качестве решения в этой ситуации. Надеюсь, это поможет кому-то.

person Nodirabegimxonoyim    schedule 23.08.2019