@testing-library/vue测试禁用状态checkbox时无法正确校验问题
问题根因
你遇到的问题是fireEvent的底层逻辑导致的:fireEvent是直接在DOM元素上触发对应事件,不会模拟浏览器的原生交互限制——真实浏览器中点击disabled的表单元素不会触发状态变更,但fireEvent会跳过这个校验,直接触发点击事件改变checkbox的选中状态,所以断言失败。
解决方案
推荐使用@testing-library/user-event代替fireEvent,这个库专门模拟真实用户的交互行为,会自动遵守浏览器的交互限制,比如禁用元素无法点击、输入要逐个敲字符等,更符合实际使用场景。
具体修改步骤
- 安装依赖(如果项目未安装):
npm install @testing-library/user-event --save-dev
- 修改测试代码:
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
相关产品推荐
相关产品推荐

