我正在尝试测试纯反应成分。
import React, {Component} from 'react';
class App extends Component {
constructor (props){
super(props);
props.init();
}
render() {
return (
<div className="container-wrapper">
{this.props.children}
</div>
);
}
}
App.propTypes = {
init : React.PropTypes.func,
children : React.PropTypes.element,
};
export default App;
import React from 'react';
import App from 'app/main/components/App';
import renderer from 'react-test-renderer';
jest.mock('react-dom');
const blank = jest.fn();
describe('App', () => {
it('Renders App', () => {
const component = renderer.create(<App init={blank}> </App>);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
当我执行测试时,我得到以下错误。
console.error node_modules/fbjs/lib/warning.js:36
Warning: Failed prop type: Invalid prop `children` of type `string` supplied to `App`, expected a single ReactElement.
in App
我可以理解,Props.children是无效的。我怎么能模仿props.children?或者是否有其他方式测试此类组件
答案 0 :(得分:2)
您只需将孩子传递到<App />
组件:
it('Renders App', () => {
const component = renderer.create(
<App init={blank}>
Hello App.
</App>
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
答案 1 :(得分:1)
之前的解决方案仍然返回字符串。您可以返回任何HTML元素
it('Renders App', () => {
const component = renderer.create(
<App init={blank}>
<div />
</App>
);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});