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

@testing-library/vue测试禁用状态checkbox时无法正确校验问题

问题根因

你遇到的问题是fireEvent的底层逻辑导致的:fireEvent是直接在DOM元素上触发对应事件,不会模拟浏览器的原生交互限制——真实浏览器中点击disabled的表单元素不会触发状态变更,但fireEvent会跳过这个校验,直接触发点击事件改变checkbox的选中状态,所以断言失败。

解决方案

推荐使用@testing-library/user-event代替fireEvent,这个库专门模拟真实用户的交互行为,会自动遵守浏览器的交互限制,比如禁用元素无法点击、输入要逐个敲字符等,更符合实际使用场景。

具体修改步骤

  1. 安装依赖(如果项目未安装):
npm install @testing-library/user-event --save-dev
  1. 修改测试代码:
import { render, screen } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';

it('should uncheck if is not disabled', async () => {
  const user = userEvent.setup();
  render({
    template: '<input data-test-id="checkbox" type="checkbox" checked />',
  });

  const el = screen.getByTestId('checkbox');
  await user.click(el);

  expect(el).not.toBeDisabled();
  expect(el).not.toBeChecked();
});

it('should check if is not disabled', async () => {
  const user = userEvent.setup();
  render({
    template: '<input data-test-id="checkbox" type="checkbox" />',
  });

  const el = screen.getByTestId('checkbox');
  await user.click(el);

  expect(el).not.toBeDisabled();
  expect(el).toBeChecked();
});

it('should not uncheck if is disabled', async () => {
  const user = userEvent.setup();
  render({
    template: '<input data-test-id="checkbox" type="checkbox" checked disabled />',
  });

  const el = screen.getByTestId('checkbox');
  await user.click(el);

  expect(el).toBeDisabled();
  expect(el).toBeChecked();
});

it('should not check if is disabled', async () => {
  const user = userEvent.setup();
  render({
    template: '<input data-test-id="checkbox" type="checkbox" disabled />',
  });

  const el = screen.getByTestId('checkbox');
  await user.click(el);

  expect(el).toBeDisabled();
  expect(el).not.toBeChecked();
});

补充说明

如果要继续使用fireEvent,需要自行在点击前判断元素是否禁用,但这种方式不符合测试库推荐的「模拟真实用户交互」的最佳实践,不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:57:04