React Snapshot testing with jest - 道具类型失败:提供的 `string` 类型的道具 `children` 无效

React Snapshot testing with jest - Failed prop type: Invalid prop `children` of type `string` supplied

我正在尝试测试一个纯 React 组件。

组件

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;

Jest 快照测试

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?或者是否有其他方法测试这些组件

您可以简单地将 child 传递给您的 <App /> 组件:

it('Renders App', () => {
    const component = renderer.create(
        <App init={blank}>
            Hello App.
        </App>
    );
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();
});

之前的解法还是returns字符串。您可以 return 任何 HTML 元素代替

it('Renders App', () => {
  const component = renderer.create(
    <App init={blank}>
      <div />
    </App>
  );
  const tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});