【问题标题】:React Snapshot testing with jest - Failed prop type: Invalid prop `children` of type `string` supplied用玩笑反应快照测试 - 道具类型失败:提供的“字符串”类型的无效道具“孩子”
【发布时间】:2017-07-14 19:16:15
【问题描述】:

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

组件

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

【问题讨论】:

    标签: unit-testing testing reactjs snapshot jestjs


    【解决方案1】:

    您可以简单地将孩子传递给您的 &lt;App /&gt; 组件:

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

    【讨论】:

    • 谢谢,我花了一些时间。但我也认为:)
    【解决方案2】:

    之前的解决方案仍然返回字符串。您可以改为返回任何 HTML 元素

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-05
      • 2020-01-22
      • 2019-03-22
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多