You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React Testing Library测试<Button/>触发SubmitEvent可不提供onSubmit吗

解决方案

你不需要在Button组件的单元测试中额外模拟提交事件或者绑定onSubmit处理器,仅需要验证Button组件正确将type prop透传给内部原生button元素即可:

  • 原生<button type="submit">处于Form元素内部时会自动触发SubmitEvent是浏览器的标准行为,不属于你的组件逻辑需要验证的范畴
  • 你的Button组件的唯一职责是正确接收外部传入的type属性并传递给内部原生节点,只要验证这一点就能满足测试要求

以下是基于React Testing Library的示例测试代码:

import { render, screen } from '@testing-library/react';
import Button from './Button';

test('传入type="submit"时透传属性给原生button', () => {
  render(<Button text="提交按钮" type="submit" />);
  const submitBtn = screen.getByLabelText('提交按钮');
  expect(submitBtn).toHaveAttribute('type', 'submit');
});

如果你使用Enzyme等其他测试工具,逻辑完全一致,仅需要定位到组件内部的原生button节点,验证其type属性值和传入的prop一致即可。

内容的提问来源于stack exchange,提问作者bitcasual

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:39:01