react-dom / test-utils,TypeError:无法读取属性' children'未定义的

时间:2017-07-12 04:49:11

标签: reactjs jestjs

我使用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>
    );

1 个答案:

答案 0 :(得分:0)

scryRenderedDOMComponentsWithClass不允许您在找到的组件上声明道具,而scryRenderedComponentsWithType则允许。有关详情,可以找到here

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

您还可以决定使用具有更简单语法的酶进行浅层渲染,并找到您的子组件及其道具,然后使用react test utils(scryRenderedDOMComponentsWithClass,scryRenderedDOMComponentsWithTag和scryRenderedComponentsWithType)的语法。 您可以阅读为什么以及更多about it here