Настройте karma.js для работы с реакцией и ES6.

Я пытаюсь разработать модуль реагирования с ES6 и не смог найти для этого никакого генератора, поэтому мне пришлось сделать его из базового. Я смог настроить почти все, но у меня много проблем, попробуйте настроить карму, чтобы протестировать мой модуль.

Это моя карма.conf.js

// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-03-17 using
// generator-karma 0.9.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['commonjs', 'mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
      'node_modules/react/react.js',
      'lib/**/*.js',
      'test/**/*.js'
    ],
    preprocessors: {
      'lib/**/*.cjsx': ['cjsx'],
      'test/**/*.cjsx': ['cjsx'],
      'lib/**/*.js': ['babel', 'commonjs'],
      'test/**/*.js': ['babel', 'commonjs']
    },
    babelPreprocessor: {
      options: {
        sourceMap: 'inline'
      },
      filename: function (file) {
        return file.originalPath.replace(/\.js$/, '.es5.js');
      },
      sourceFileName: function (file) {
        return file.originalPath;
      }
    },

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

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      'Chrome', 'PhantomJS'
    ],

    // Which plugins to enable
    plugins: [
      'karma-commonjs',
      'karma-cjsx-preprocessor',
      'karma-babel-preprocessor',
      'karma-phantomjs-launcher',
      'karma-chrome-launcher',
      'karma-mocha',
      'karma-chai'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

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

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};

На данный момент у меня есть следующая ошибка

Chrome 42.0.2311 (Mac OS X 10.10.2) ERROR
  Uncaught ReferenceError: module is not defined
  at /Users/admin/workspace/open_source/react-component-inspector/node_modules/react/react.js:1

и если я удалю ссылку на реакцию из раздела файлов, я получу эту другую ошибку

PhantomJS 1.9.8 (Mac OS X) ERROR
  Uncaught Error: Could not find module 'react' from '/Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js'
  at /Users/admin/workspace/open_source/react-component-inspector/node_modules/karma-commonjs/client/commonjs_bridge.js:85

И если я удалю commonJS, я получу

PhantomJS 1.9.8 (Mac OS X) ERROR
  ReferenceError: Can't find variable: exports
  at /Users/admin/workspace/open_source/react-component-inspector/lib/index.es5.js:5

Или, по крайней мере, кто-нибудь может порекомендовать мне генератор йо с кармой, ES6, jsx для создания модуля, а не веб-приложения?

Спасибо за помощь


person Spike886    schedule 17.03.2015    source источник


Ответы (1)


Я считаю, что вам просто нужно добавить путь к файлу реакции в список файлов препроцессора. Это связано с тем, что файл реакции также использует формат commonjs, как и файлы вашего приложения, и когда этот файл загружается в хром, в отличие от узла, браузер не имеет представления о том, откуда взялся объект «модуль». Обновленный отрывок из вашего кода ниже.

        // list of files / patterns to load in the browser
        files: [
          'node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
          'node_modules/react/react.js',
          'lib/**/*.js',
          'test/**/*.js'
        ],
        preprocessors: {
          // you can probably leave off babel here.
          'node_modules/react/react.js': ['babel', 'commonjs'],
          'lib/**/*.cjsx': ['cjsx'],
          'test/**/*.cjsx': ['cjsx'],
          'lib/**/*.js': ['babel', 'commonjs'],
          'test/**/*.js': ['babel', 'commonjs']
        },
person Cole Reed    schedule 02.04.2015