我用 ES6 编写了我的 React 应用程序。现在我也想用 ES6 编写我的测试。所以这里的挑战是配置 karma 。
与谷歌一起,我用 karma.config.js 走到了这一步(我省略了配置文件中相同的部分!):
...
files: [
'../node_modules/karma-babel-preprocessor/node_modules/babel-core/browser-polyfill.js',
'../app/**/*.jsx',
'../test/**/*.jsx'],
preprocessors: {
'app/**/*.jsx': ['react-jsx', 'babel'],
'test/**/*.jsx': ['react-jsx', 'babel']
},
'babelPreprocessor': {
options: {
sourceMap: 'inline'
},
filename: function(file) {
return file.originalPath.replace(/\.jsx$/, '.es5.js');
},
sourceFileName: function(file) {
return file.originalPath;
}
},
....
我认为此设置应该做什么:1) 将 JSX 编译为 JS,然后 babel
应该将 ES6 转换为 ES5。这与 polyfill
一起我预计它应该在 phantomjs 中运行,例如。但是不,这是我运行时 karma 的输出:
PhantomJS 1.9.8 (Mac OS X) ERROR
SyntaxError: Parse error
at Projects/ES6/app/js/app.jsx:35
PhantomJS 1.9.8 (Mac OS X): Executed 0 of 0 ERROR (0.027 secs / 0 secs)
[20:36:59] Karma has exited with 1
app.jsx
的第 35 行包含实际的 JSX 部分。所以,出于某种原因,预处理器似乎没有那么多。如果您对预处理器有任何帮助,我们将不胜感激?
更新:我有这个几乎可以工作的酒。原来我的预处理器应该这样交换
'../app/**/*.jsx': ['babel', 'react'],
'../test/**/*.jsx': ['babel', 'react']
现在,当我运行它时,我得到:
Uncaught ReferenceError: require is not defined
我以为我有一个 polyfill :(
最佳答案
我将 ES6 与 Browserify 和 JSX 结合使用。对于编译,我使用 Babel。以下配置适用于我。
karma.conf.js
...
frameworks: ['browserify', 'jasmine'],
files: [
'Component.js', // replace with your component
'__tests__/Component-test.js'
],
preprocessors: {
'Component.js': 'browserify',
'./__tests__/Component-test.js': 'browserify'
},
browserify : {
transform : ['babelify']
},
...
__tests__/Component-test.js
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var Component = require('../Component.js');
describe('Component', () => {
it('should work', () => {
var component = <Component />;
TestUtils.renderIntoDocument(component);
expect(component).toBeTruthy();
});
});
如果您有任何问题,请告诉我。
关于javascript - 如何使用 KARMA 对 React JSX ES6 代码进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437997/