scryRenderedComponentsWithType 返回一个空数组

问题描述 投票:0回答:1

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

it('has 7 NavBarItems', () => {
    const component = ReactTestUtils.renderIntoDocument(<App />);
    const navBarItems = ReactTestUtils.scryRenderedComponentsWithType(
        component,
        NavBarItem);

    expect(navBarItems.length).toEqual(7);
});

App
组件在非测试环境中渲染时,会在屏幕顶部创建一个带有 7 个 NavBarItem 子组件的 NavBar,以方便在整个应用程序中进行导航。

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
的文件对
NavBarItem
进行添加调用也是如此。是我用错了,还是我想要的根本不可能?

reactjs testing jestjs
1个回答
0
投票
  1. 确保您已将
    react
    react-dom
    以及
    App
    NavBarItem
    组件导入到测试中。如果我们看不到整个文件,就很难提供帮助。

...如果这没有帮助:
您尝试过其他方法吗?喜欢:

scryRenderedDOMComponentsWithClass(component, NavBarItem);`
© www.soinside.com 2019 - 2024. All rights reserved.