scryRenderedComponentsWithType返回一个空数组

时间:2017-02-15 23:56:49

标签: reactjs testing jestjs

我对React应用程序进行了以下测试:

state

在非测试环境中呈现it('has 7 NavBarItems', () => { const component = ReactTestUtils.renderIntoDocument(<App />); const navBarItems = ReactTestUtils.scryRenderedComponentsWithType( component, NavBarItem); expect(navBarItems.length).toEqual(7); }); 组件时,会在屏幕顶部创建一个包含7个NavBarItem子组件的NavBar,以方便在整个应用程序中导航。

App类如下:

NavBarItem

但是,测试总是失败,因为class NavBarItem extends Component { render() { return ( <div id={this.props.id} className={"NavBarItem" + (this.props.active ? " active" : "") + (this.props.visible ? "" : " hidden")} onClick={e => this.props.navBarClick(e.target.id)}> {this.props.title} </div> ); } } 总是返回一个空数组,即使我为scryRenderedComponentsWithType添加jest.dontMock的调用以及App的文件也是如此。导入。我使用它错了,还是我想要的不可能?

1 个答案:

答案 0 :(得分:0)

  1. 确保您已将reactreact-dom导入测试,以及AppNavBarItem组件。如果我们无法查看整个文件,那么就很难提供帮助。
  2. ......如果这没有帮助: 你尝试过其他方法吗?像:

    scryRenderedDOMComponentsWithClass( component, NavBarItem)