React 测试库:对象作为 React 子项无效

React Testing Library: Objects are not valid as a React child

我正在尝试使用 jest 编写测试,但我遇到了这个错误

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
        in td (created by TableCell)
        in TableCell (created by DataTable)
        in tr (created by TableExpandRow)
        in TableExpandRow (created by DataTable)
        in tbody (created by TableBody)
        in TableBody (created by DataTable)
        in table (created by Table)
        in Table (created by DataTable)
        in div (created by DataTable)
        in div (created by TableContainer)
        in TableContainer (created by DataTable)
        in div (created by DataTable)
        in DataTable
        in Unknown
        in Unknown (created by EnhancedDataTable)
        in EnhancedDataTable (created by MyPage)
        in div (created by MyPage)
        in MyPage


  27 | 
  28 |     it('renders', () => {
> 29 |         const { container } = render(<MyPage />);

MyPage 是 returns

的功能组件
<React.Fragment>
    <MyHeader title={'Page Header'} />
    <div className="page-content">
        <EnhancedDataTable
            actions={actions}
            rowActions={rowActions}
            headers={rowHeaders}
            rowDetail={rowDetail}
            rows={rowsData}
            className='my-table'
        />
    </div>
</React.Fragment>

我在这里错过了什么?

您正在尝试将 object(承诺)呈现为 child。从你的代码中很难知道在哪里,但是,假设你的 table 像 rc-components table 一样工作,它可能是这样的:

假设我有一个数组并想将其渲染为 table

const arr = [
  {
    company: 'XYZ',
    owner: {
      name: 'Julius'
    }
  }
]

现在,我想在 table 中呈现它,其中包含以下列: |公司|所有者 |,所以我创建了一个 headers 数组:

const arr = [
  {
    dataIndex: 'company'
  },
  {
    dataIndex: 'owner'
  }
]

现在,这行不通了,因为我的 table 会尝试渲染 object {name: 'Julius'},并且 object 无效,因为反应 child仁.

修复方法是将我的 headers 更改为:

const arr = [
  {
    dataIndex: 'company'
  },
  {
    dataIndex: ['owner', 'name']
  }
]

现在它应该可以工作了,因为列将是 row['owner']['name'],一个字符串。

如果没有更多代码,很难准确判断问题出在哪里,但希望该示例能让您了解 react 对该错误意味着什么。我所知道的是,错误出在您 table 的单元格中的某处,因为堆栈显示 in Unknown (created by EnhancedDataTable) 并且最后(或者我猜是第一个)项目是 td,一个常见的table 数据的元素。