Jest测试触发click事件报错:无法获取对应DOM元素如何解决?
问题根因梳理
queryByTestId返回null:React Testing Library的*ByTestId系列API查询的是元素的data-testid自定义属性,你只给元素加了原生id属性,没有加data-testid,因此无法匹配到元素getElementsByClassName返回空HTMLCollection:该API仅支持传入单个类名作为参数,不支持复合选择器,且返回的是类数组对象,无法直接传入fireEvent.click使用- 混用API报错:你使用的
container.find是Enzyme库的方法,而你引入的是React Testing Library,原生DOM节点没有find方法,因此无法查询到元素 - 元素未渲染:如果传入
TableWrapper的props中isCheckBox为false、headers数组为空,或者对应列未开启sortable,目标元素根本不会生成,自然无法定位
解决方案
第一步:给目标元素添加data-testid属性(React Testing Library最佳实践,不受类名、结构变化影响)
修改TableHead组件代码:
// 全选复选框添加data-testid <input id="selectAllCheckBox" data-testid="select-all-checkbox" className={`${mainClass}__checkBox`} type="checkbox" onClick={selectAllChecked} ref={checkRef} /> // 排序图标添加data-testid <Icon id="sortIcon" data-testid="sort-icon" className={`${mainClass}__sort-icon`} icon={SortIcon} color={"midnightblue"} height="16px" onClick={() => handleSorterChange(key.toLowerCase(), sortOrder) } />
第二步:确保传入的Props正确
渲染TableWrapper时要保证以下参数正确传递,否则目标元素不会渲染:
const props = { // 其他业务必要参数 isCheckBox: true, // 开启表头复选框展示 headers: [ { header: '列名1', key: 'col1', sortable: true }, // 要测试排序的列需要开启sortable // 其他表头配置 ], selectAllChecked: jest.fn(), // 模拟回调函数 sortColumn: jest.fn() // 模拟排序回调 }
第三步:修正测试用例代码
// 测试全选复选框点击 it("Select all checkBox to be clicked", () => { render(<TableWrapper {...props} />); // 用getByTestId查询,找不到会直接抛出明确错误,方便定位问题 const selectAllCheckbox = screen.getByTestId("select-all-checkbox"); fireEvent.click(selectAllCheckbox); // 验证回调触发和勾选状态 expect(props.selectAllChecked).toHaveBeenCalled(); expect(selectAllCheckbox).toBeChecked(); }); // 测试排序图标点击 it("sort icon click should trigger sort callback", () => { render(<TableWrapper {...props} />); const sortIcon = screen.getByTestId("sort-icon"); fireEvent.click(sortIcon); expect(props.sortColumn).toHaveBeenCalled(); });
可选方案(无需加data-testid)
如果你不想添加data-testid,也可以用原生选择器查询:
// 通过id查询复选框 const selectAllCheckbox = screen.getById("selectAllCheckBox"); // 或者通过类名查询 const selectAllCheckbox = container.querySelector(".oct-cors-TableWrapper__checkBox");
内容的提问来源于stack exchange,提问作者Enigmatic
相关产品推荐
相关产品推荐

