我正在遵循Jest 教程来测试 React 组件,并且我的 jsx 遇到了预处理问题。我认为错误是由于预处理造成的,错误消息不是很有帮助。谷歌搜索显示了与旧版本的 react/jest 类似的错误,这些错误是通过包含/** @jsx React.DOM */
docblock修复的,据我所知已修复。
当我运行测试时:
Using Jest CLI v0.8.0, jasmine1
FAIL spec/MyComponent_spec.js
Runtime Error
SyntaxError: /Users/asdf/react/stuff-react/spec/MyComponent_spec.js: Unexpected token (13:6)
npm ERR! Test failed. See above for more details.
有问题的那一行是应该渲染我的组件的那一行:
jest.dontMock('../src/MyComponent');
let React = require('react');
let ReactDOM = require('react-dom');
let TestUtils = require('react-addons-test-utils');
const MyComponent = require('../src/MyComponent');
describe('MyComponent', function(){
it('render', function(){
var myComponent = TestUtils.renderIntoDocument(
// This is the line referenced in the test error
<MyComponent />
)
var myComponentNode = ReactDOM.findDOMNode(myComponent);
expect(myComponentNode.textContent).toEqual('hi');
});
});
我认为我package.json
有责任告诉 jest 预处理该文件?
"scripts": {
"test": "jest"
},
"jest": {
"testDirectoryName": "spec",
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs"
]
},
我的组件:
import React from 'react';
class MyComponent extends React.Component({
render () {
return (
<div>
hi
</div>
)
}
});
export default MyComponent;