我正在构建一个简单的网站来使用 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/