【问题标题】:Jasmine Tests give error "Uncaught ReferenceError: require is not defined"Jasmine 测试给出错误“未捕获的 ReferenceError:未定义要求”
【发布时间】:2015-11-14 19:50:06
【问题描述】:

我正在尝试在我的 React 站点上使用 Karma 运行 Jasmine 测试。我的测试以前可以正常工作,但我不确定发生了什么变化,但现在我得到了错误:

Uncaught ReferenceError: require is not defined

对于 Chrome 和 PhantomJS 和 Firefox 给我类似的错误。如果更多信息会有所帮助,请告诉我。我在网上找到了很多类似的问题,但没有任何解决问题的方法。

你可以看到下面的测试文件,完整的项目在my github repo

提前致谢!

我的测试文件如下所示:

var React = require('react/addons');
var Story = require('../../app/js/components/story.jsx');
var TestUtils = React.addons.TestUtils;
var testUtilsAdditions = require('react-testutils-additions');

  describe('Story component', function () {
    var component;

    beforeEach(function () {
      var element = React.createElement(Story);
      element.props.data = {
        storyTitle: 'front end test title',
        author : 'front end author',
        storyText : 'front end story text'
      };
      component = TestUtils.renderIntoDocument(element);
      });

    it('should display a story', function () {
      expect(component.props.data).toBeDefined();
      expect(component.props.data.storyTitle).toBeDefined();
      expect(component.props.data.storyTitle).toBe('front end test title');
      expect(component.props.data.author).toBe('front end author');
      expect(component.props.data.storyText).toBe('front end story text');
    });

  });

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

// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)

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: [
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
        'test/karma_tests/*test.js'
    ],

    //plugins to start browsers
    plugins : [
    'karma-junit-reporter',
    'karma-phantomjs-launcher',
    'karma-chrome-launcher',
    'karma-firefox-launcher',
    'karma-opera-launcher',
    'karma-ie-launcher',
    'karma-jasmine',
    'karma-chai',
    'karma-webpack'
    ],


    // 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/karma_tests/*test.js': ['webpack'],
        // 'test/**/*_test.js': ['webpack']
    },

    webpack: {
            // karma watches the test entry points
            // (you don't need to specify the entry option)
            // webpack watches dependencies

            // webpack configuration
        module: {
          loaders: [{
            test: /\.jsx$/,
            loader:'jsx-loader'
          }]
        }
        },


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


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome', 'Firefox', 'PhantomJS'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};

这是我在进行@guilhebl 推荐的更改后得到的错误:

Firefox 40.0.0 (Ubuntu 0.0.0) ERROR
  Error: Module name "react/addons" has not been loaded yet for context: _. Use require([])
  http://requirejs.org/docs/errors.html#notloaded
  at /home/michael/repository/short-stories/node_modules/requirejs/require.js:165

这是我进行更改后的 karma.conf.js:

// Karma configuration
// Generated on Thu Jul 02 2015 15:56:34 GMT-0700 (PDT)

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: [
    './node_modules/phantomjs-polyfill/bind-polyfill.js',
    './node_modules/requirejs/require.js',
    './node_modules/karma-requirejs/lib/adapter.js',
    './test/karma_tests/*test.js'
    ],

    //plugins to start browsers
    plugins : [
    'karma-junit-reporter',
    'karma-phantomjs-launcher',
    'karma-chrome-launcher',
    'karma-firefox-launcher',
    'karma-opera-launcher',
    'karma-ie-launcher',
    'karma-jasmine',
    'karma-chai',
    'karma-webpack',
    'karma-requirejs',
    'karma-script-launcher'
    ],


    // 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/karma_tests/*test.js': ['webpack'],
        // 'test/**/*_test.js': ['webpack']
    },

    webpack: {
            // karma watches the test entry points
            // (you don't need to specify the entry option)
            // webpack watches dependencies

            // webpack configuration
        module: {
          loaders: [{
            test: /\.jsx$/,
            loader:'jsx-loader'
          }]
        }
        },


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


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome', 'Firefox', 'PhantomJS'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};

【问题讨论】:

  • 看起来你的 webpack 构建可能发生了一些事情 - webpack 应该定义 require 并使其可用于你的 js 文件。你在 webpack 设置中玩过什么吗?
  • 感谢 theWanderer4865。除了用它构建之外,我还没有对 webpack 做任何事情。我将我的 karma.conf.js 文件添加到我的问题中,以便您查看它是如何设置的。

标签: javascript unit-testing reactjs jasmine karma-jasmine


【解决方案1】:

您应该已经在 karma.conf 文件中配置了 require,例如:

module.exports = function(config){
  config.set({
    frameworks: ['jasmine'],

    plugins : [               
               'karma-chrome-launcher',
               'karma-firefox-launcher',                            
               'karma-script-launcher',
               'karma-phantomjs-launcher',
               'karma-jasmine',
               'karma-requirejs'               
    ],

    files : [          
      'node_modules/requirejs/require.js',
      'node_modules/karma-requirejs/lib/adapter.js',      
      'app/js/test-main.js',

      {pattern: 'app/lib/**/*.js', included: false},
      {pattern: 'app/js/**/*.js', included: false},      
      {pattern: 'app/js/views/**/*Test.js', included: false}      
    ],

    browsers: ['PhantomJS']        
  });
};

【讨论】:

  • 谢谢 guilhebl。我编辑了我的 karma.conf.js 以使用 karma-requirejs 和 requirejs,就像你展示的那样,但现在我收到错误 ``` Uncaught Error: Module name "react/addons" has not been loaded yet for context: _.使用 require([])```
  • @CascadiaJS 你能用你所做的这个答案的更改以及你得到的堆栈跟踪来更新你的问题吗?
猜你喜欢
  • 1970-01-01
  • 2015-09-03
  • 2020-07-13
  • 2018-01-25
  • 2019-04-23
  • 2022-06-15
  • 2021-10-06
  • 2020-05-16
  • 2012-12-16
相关资源
最近更新 更多