React按钮组件测试报Element type is invalid错误如何解决?
问题修复方案
核心报错修复(解决Element type is invalid报错)
你的Button组件是默认导出(export default function Button()),但测试代码中使用了命名导入,导致导入的Button为undefined,直接触发该报错。
将测试文件中的导入语句修改即可:
- import { Button } from "./Button"; + import Button from "./Button";
其他测试逻辑错误修复
你的测试代码还存在多处逻辑错误,会导致后续测试运行失败,需要同步修改:
1. 缺失依赖导入与调用错误
- 测试中使用的
userEvent没有导入,getByRole没有通过screen调用,第一个测试用例没有给Button传text属性,无法匹配到/click me/i的按钮 - 修复后第一个测试用例代码:
// 顶部新增导入 import userEvent from '@testing-library/user-event'; it("will call onClick when enabled", async () => { const user = userEvent.setup(); const onClick = jest.fn(); render( <Router> <Button onClick={onClick} disabled={false} text="click me" /> </Router> ); await user.click(screen.getByRole("button", {name: /click me/i})); expect(onClick).toHaveBeenCalledTimes(1); });
2. 第二个测试用例查询方法全部误用
getAllByText返回数组,不能直接使用toBeInTheDocument匹配,应该用getByText- button的type属性、size、variant属于组件属性/样式配置,不会作为文本、显示值、placeholder出现在DOM中,不能用
queryByText、queryAllByDisplayValue、queryByPlaceholderText查询 - 你传入的type为大写
Submit,不符合组件propTypes定义的小写可选值,会触发propTypes警告,需要改为小写submit - 修复后第二个测试用例代码:
it("should activate a button", () => { render( <Router> <Button text="Add Project" type="submit" size="md" variant="blue" /> </Router> ); const buttonEl = screen.getByRole("button", {name: /Add Project/i}); expect(buttonEl).toBeInTheDocument(); expect(buttonEl).toHaveAttribute("type", "submit"); expect(buttonEl).toHaveClass("px-4", "py-2", "text-sm"); // 对应size=md的样式 expect(buttonEl).toHaveClass("bg-blue-600"); // 对应variant=blue的样式 });
组件可选优化
组件中disabled的判断可以简化,不影响功能但更简洁:
- disabled={disabled && disabled} + disabled={disabled}
内容的提问来源于stack exchange,提问作者Payton Curry
相关产品推荐
相关产品推荐

