【问题标题】:react-dom/test-utils, TypeError: Cannot read property 'children' of undefinedreact-dom/test-utils,TypeError:无法读取未定义的属性“孩子”
【发布时间】:2017-07-12 04:49:10
【问题描述】:

我使用react-dom/test-utils 来测试我的反应组件。

但是scryRenderedDOMComponentsWithClass的返回值没有props

props.children 属性。我是不是做错了什么?

这是我的测试代码:

it('renders item count correctly', () => {
    const $$searchList  = TestUtils.renderIntoDocument(<SearchList items={datas}/>)
    const list = TestUtils.scryRenderedDOMComponentsWithClass($$searchList, 'list');

    expect(list.props.children).toHaveLength(4);
    expect(items).toHaveLength(4);

  });

这是测试结果:

● component - SearchList test suites › renders item count correctly

    TypeError: Cannot read property 'children' of undefined

      at Object.<anonymous> (src/components/List/__tests__/SearchList.test.jsx:17:26)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

  component - SearchList test suites
    ✓ loads without error (43ms)
    ✕ renders item count correctly (18ms)

-- 更新--

这是我的组件渲染:

return (
      <div className="list">
        {
          items.map((item: Book, idx: number): React.ReactElement<IListProps<Book>> => {
            return (
              <ListItem onClick={() => this.onItemClick(item, idx)} key={item.id} item={item}/>
            );
          })
        }
      </div>
    );

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    scryRenderedDOMComponentsWithClass 不允许您在找到的组件上声明 props,而 scryRenderedComponentsWithType 可以。更多信息请见here

    在 React 0.14 之前,scry/find...WithClass 会返回 DOM 组件。随着 0.14 的发布,这些方法返回 DOM 节点本身。在这两种情况下,复合组件的 props 都不可访问。

    您还可以决定使用酶,它具有更简单的语法来进行浅层渲染和查找子组件及其道具,然后是反应测试工具的语法(scryRenderedDOMComponentsWithClass、scryRenderedDOMComponentsWithTag 和 scryRenderedComponentsWithType)。 你可以阅读原因和更多about it here

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2019-02-19
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 2021-11-24
      • 2019-07-19
      • 2020-08-08
      相关资源
      最近更新 更多