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

Jest FireEvent点击禁用按钮返回True的测试问题求助

问题分析与解决方案

核心问题拆解

  1. fireEvent.click返回true的本质:fireEvent.click()的返回值仅表示事件被成功模拟触发,它不会自动遵循浏览器对禁用元素的点击拦截规则——哪怕按钮是禁用状态,这个方法也会返回true,但浏览器实际并不会执行禁用按钮的onClick回调。
  2. 测试断言错误:原测试里的expect(BUTTON).toBeEnabled()和预期完全相反,应该断言按钮处于禁用状态。
  3. 缺少关键验证:没有校验禁用状态下点击按钮时,onAbstainVote回调不会被调用。

修正后的测试代码

describe('[ABSTAIN VOTE BUTTON] Testing OnClick...', () => {
    test('Should NOT trigger onClick when button is disabled', async () => {
        const handleClick = jest.fn();
        render(<AbstainVoteButton onAbstainVote={handleClick} isDisabled={true} />);
        const BUTTON = screen.getByText(/Abstain from Voting/i);

        // 模拟点击禁用按钮
        fireEvent.click(BUTTON);

        // 断言按钮处于禁用状态
        expect(BUTTON).toBeDisabled();
        // 断言回调未被调用
        expect(handleClick).not.toHaveBeenCalled();
    });
});

进阶优化(更贴近真实用户交互)

如果想要模拟更贴近浏览器的真实行为,可以使用@testing-library/user-event的userEvent.click(),它会自动忽略禁用元素的点击,逻辑更贴合真实用户操作:

// 先安装依赖:npm install @testing-library/user-event --save-dev
import userEvent from '@testing-library/user-event';

describe('[ABSTAIN VOTE BUTTON] Testing OnClick...', () => {
    test('Should NOT trigger onClick when button is disabled', async () => {
        const user = userEvent.setup();
        const handleClick = jest.fn();
        render(<AbstainVoteButton onAbstainVote={handleClick} isDisabled={true} />);
        const BUTTON = screen.getByText(/Abstain from Voting/i);

        await user.click(BUTTON);

        expect(BUTTON).toBeDisabled();
        expect(handleClick).not.toHaveBeenCalled();
    });
});

内容的提问来源于stack exchange,提问作者THIAGO DE BONIS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:15:45