首页 > 解决方案 > ReactJS:在测试 HOC 组件时,渲染没有返回任何内容

问题描述

我有以下代码:

TableWrapper.jsx

const TableWrapper = props => {
    return (
      <div>
        {props.table}
      </div>
    );
}

然后它被用于Foo.jsx

export class FooTable extends React.Component {
  render() {
    return (
      <div>
        <TableWrapper
          table={<ListTable />}
        />
      </div>
    );
  }
}

这是ListTable.jsx

  render() {
    const {data, error, asyncStatus} = this.props.instanceList;
    return (
      <div>
        <CustomTable
           title='123'
        />
      </div>
    )
  }

我使用 jest 和酵素进行其中一项测试:

    it('Simulate search input field', () => {
      const container = mount(<FooTable {...mockProps} />);
    });
  });

我正进入(状态

   console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Uncaught [Invariant Violation: TableWrapperComponent(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.]

如果我使用shallow我不会出错。我错过了什么?

标签: reactjsenzyme

解决方案


您应该使用渲染,然后将您的组件放入您的渲染道具中。

<TableWrapper render={table => <ListTable props={...this.props} />} />

现在我会问您在 ListTable 中使用的 CustomTable 在哪里?在某些时候,您将不得不制作一个初始组件或使用许多库中的一个。

const myGenericComponent = (props) => {  
 // create variables deconstruct props as you like
const name = props.name 
    return (
// assuming I passed in name from my parent component as one of my props
      <div><table><th>Table {name}</th><td>{name}</td></table>
  )  
}
export default myGenericComponent;

推荐阅读