React16.2中Jest+React Renderer测试JSX数组遇元素查找问题求助
解决React-test-renderer无法找到数组中后续元素的问题
你遇到的核心问题是:react-test-renderer在直接处理元素数组时,默认的root仅指向数组的第一个元素,后续元素以兄弟节点形式存在,没法直接通过root.findByProps定位。下面给你两种实用的解决方案:
方案一:用临时容器包裹元素数组(推荐)
这是最灵活且易维护的方法,把renderButtons返回的Button数组包裹在一个<div>中,让所有Button成为该容器的子元素,之后就能正常用findByProps定位任意Button了:
// Comp.test.js test('.renderButtons', () => { const comp = new Comp(); // 用div包裹返回的Button数组,统一管理子元素 const component = renderer.create(<div>{comp.renderButtons()}</div>); const root = component.root; // 现在可以成功找到任意一个Button const secondButton = root.findByProps({ key: 'second' }); const thirdButton = root.findByProps({ key: 'third' }); // 测试onClick逻辑:用jest监听console.log const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); // 调用第二个Button的点击事件,验证输出 secondButton.props.onClick(); expect(consoleSpy).toHaveBeenCalledWith('bar'); // 调用第三个Button的点击事件,验证输出 thirdButton.props.onClick(); expect(consoleSpy).toHaveBeenCalledWith('baz'); // 清理监听,避免影响其他测试 consoleSpy.mockRestore(); });
方案二:通过兄弟节点访问后续元素
如果不想额外添加容器,也可以利用nextSibling遍历兄弟节点,但这种方法在元素数量变动时灵活性较差:
test('.renderButtons', () => { const comp = new Comp(); const component = renderer.create(comp.renderButtons()); const root = component.root; // 直接通过兄弟节点获取对应Button const firstButton = root; const secondButton = root.nextSibling; const thirdButton = root.nextSibling.nextSibling; // 测试onClick功能 const consoleSpy = jest.spyOn(console, 'log').mockImplementation(); secondButton.props.onClick(); expect(consoleSpy).toHaveBeenCalledWith('bar'); consoleSpy.mockRestore(); });
原方法失效的原因
当你直接把元素数组传给renderer.create时,React测试渲染器会将数组第一个元素作为根节点,剩余元素会成为根节点的兄弟节点。而root.findByProps只会在当前节点的子元素中查找,不会遍历兄弟节点,因此无法直接定位到第二个及以后的Button。
内容的提问来源于stack exchange,提问作者EnbyCherry
相关产品推荐
相关产品推荐

