使用react-testing-library测试条件渲染翻页按钮无法找到元素问题
问题解决方法
核心原因
- Jest+jsdom测试环境默认不会计算元素的实际布局宽高,你组件里用到的
scrollWidth和clientWidth默认返回值都是0,满足node?.scrollWidth <= node?.clientWidth的条件,showRightPager被设为true,所以右侧翻页按钮不会被渲染,自然定位不到。 - 你修改
window.innerWidth的操作只会调整窗口全局尺寸,不会作用于组件内部的ScrollableArea元素,对判断逻辑没有影响。 - 补充逻辑校验:当前组件逻辑是内容宽度小于等于容器宽度(无滚动溢出)时隐藏翻页按钮,只有内容溢出时才会显示按钮,要触发按钮显示必须保证
scrollWidth > clientWidth。
调整方案
直接mockScrollableArea元素的尺寸属性,让它满足内容溢出的条件即可,测试代码修改如下:
test('should show pager buttons', () => { // mock元素尺寸,让内容宽度大于容器宽度,触发翻页按钮显示 Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, value: 1440 }) Object.defineProperty(HTMLElement.prototype, 'scrollWidth', { configurable: true, value: 2000 // 大于clientWidth即可 }) render(<Basic />); const rightPager = screen.getByTestId('right-pager'); expect(rightPager).toBeInTheDocument(); // 测试完成后删除mock,避免影响其他测试用例 delete HTMLElement.prototype.clientWidth; delete HTMLElement.prototype.scrollWidth; });
如果你的组件渲染有异步逻辑,可以把getByTestId换成异步的findByTestId兜底等待状态更新:
const rightPager = await screen.findByTestId('right-pager');
内容的提问来源于stack exchange,提问作者Matthew Benjamin
相关产品推荐
相关产品推荐

