【问题标题】:Jasmine test for React causes Webpack build to failReact 的 Jasmine 测试导致 Webpack 构建失败
【发布时间】:2015-07-04 20:00:40
【问题描述】:

我正在构建一个简单的网站来展示使用 React 的故事。我已经制作了显示所有故事的第一页,所以我想设置我的第一个测试。我是测试 React 的新手,但我对 Jasmine 做了一些工作,所以我使用 Jasmine 进行测试。我认为我已经正确设置了我的测试文件,但是当我尝试使用 Webpack 构建时,我收到以下错误:

Module parse failed: /home/michael/repository/short-stories/test/karma_tests/story_test.js Line 14: Unexpected token <
You may need an appropriate loader to handle this file type.

我的测试文件如下所示:

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

  describe('Story component', function () {

    afterEach(function () {
      if (component && TestUtils.isCompositeComponent(component) && component.isMounted()) {
        React.unmountComponentAtNode(component.getDOMNode().parent);
      }
    });

    beforeEach(function () {
      component = TestUtils.renderIntoDocument(<Story />);
      component.props.data.storyTitle = 'front end test title';
      component.props.data.author = 'front end author';
      component.props.data.storyText = 'front end story text';
    });

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

  });

我的 Gruntfile.js 中的 webpack 任务如下所示:

 webpack: {
      client: {
        entry: __dirname + '/app/js/client.jsx',
        output: {
          path: 'build/',
          file: 'bundle.js'
        },
        module: {
          loaders: [
          {
            test: /\.jsx$/,
            loader:'jsx-loader'
          }]
        }
      },
      test: {
        entry: __dirname + '/test/client/test.js',
        output: {
          path: 'test/client/',
          file: 'bundle.js'
        }
      },
      karma_test: {
        entry: __dirname + '/test/karma_tests/test_entry.js',
        output: {
          path: 'test/karma_tests/',
          file: 'bundle.js'
        }
      }
    },

如果更多信息有助于找到解决方案,请告诉我。你可以在我的 github repo 上查看完整的项目:https://github.com/mrbgit/short-stories/tree/react-tests

【问题讨论】:

    标签: testing jasmine reactjs webpack


    【解决方案1】:

    Webpack 无法解析您的代码。您在 JS 文件中使用 JSX 语法。 renderIntoDocument 接受一个 React 元素实例

    component = TestUtils.renderIntoDocument(React.createElement('story'));
    

    【讨论】:

    • 感谢 M_rivermount,加上将 jsx-loader 添加到 karma 测试,构建工作。但是现在当我运行测试时出现错误:“ReferenceError: require is not defined”
    • 我更新了我的答案。它超出了这个问题的范围,但没有定义 require 因为你需要在 Karma 中使用 webpack 作为预处理器,或者你需要包含已经处理的文件,在你的情况下是 karma_tests/bundle.js
    • 感谢 M_rivermount,构建现在运行。接下来我需要努力让测试正常运行!
    猜你喜欢
    • 2017-03-23
    • 2021-05-08
    • 1970-01-01
    • 2018-04-29
    • 2021-11-30
    • 1970-01-01
    • 2017-07-18
    • 2021-09-21
    • 2016-04-13
    相关资源
    最近更新 更多