testing - React 的 Jasmine 测试导致 Webpack 构建失败

标签 testing jasmine reactjs webpack

我正在构建一个简单的网站来使用 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 存储库上查看完整项目:https://github.com/mrbgit/short-stories/tree/react-tests

最佳答案

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

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

关于testing - React 的 Jasmine 测试导致 Webpack 构建失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31224663/

相关文章:

testing - 关于出于测试目的存在于类中的 Watir 问题

javascript - 测试每个元素是否包含带有 Protractor 的元素

unit-testing - 单元测试中的性能测试

forms - 测试中如何生成flask_wtf Form的post请求数据

angularjs - 将 angular-seed jasmine 单元测试转换为 coffeescript

javascript - 多个 3 列布局的目标中间 child

javascript - 尝试在 React 应用程序中使用 "Export not found"NPM 包时出现 "azure-maps-animations"错误消息

angular - 我无法在 Angular 的组件测试中比较日期

Angular 2 Jasmine 如何测试组件的功能

html - CSS:3 或 4 列,具体取决于设备方向