我对 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
进行添加调用也是如此。是我用错了,还是我想要的根本不可能?
react
和 react-dom
以及 App
和 NavBarItem
组件导入到测试中。如果我们看不到整个文件,就很难提供帮助。...如果这没有帮助:
您尝试过其他方法吗?喜欢:
scryRenderedDOMComponentsWithClass(component, NavBarItem);`