如何使用React Testing Library测试输入框的禁用状态与值
React输入框单元测试(禁用状态、值)
你的测试代码问题说明
screen.getByText('Enter text...')无法找到元素:Enter text...是输入框的placeholder属性值,不是页面渲染的文本内容,getByText只能查找可见的文本节点。screen.getByRole('input')错误:输入框对应的ARIA role是textbox,而非input,所以这个查询会失败。
正确的测试方案
1. 获取输入框元素
推荐用placeholder直接定位,因为你的输入框有明确的占位符:
const input = screen.getByPlaceholderText('Enter text...');
也可以通过role定位(text类型输入框的默认role是textbox):
const input = screen.getByRole('textbox');
2. 测试输入框可见性
expect(input).toBeVisible();
3. 测试输入框的值
直接断言元素的value属性:
expect(input).toHaveValue('test');
4. 测试禁用状态(基于aria-disabled属性)
你的输入框使用aria-disabled而非原生disabled属性,所以需要断言该属性的值:
// 测试未禁用状态 expect(input).toHaveAttribute('aria-disabled', 'false'); // 如果后续有禁用场景,测试禁用状态 // expect(input).toHaveAttribute('aria-disabled', 'true');
完整测试示例
import { render, screen } from '@testing-library/react'; import YourComponent from './YourComponent'; test('输入框状态与值测试', () => { render(<YourComponent />); // 获取输入框 const input = screen.getByPlaceholderText('Enter text...'); // 断言可见性 expect(input).toBeVisible(); // 断言值 expect(input).toHaveValue('test'); // 断言未禁用 expect(input).toHaveAttribute('aria-disabled', 'false'); });
内容的提问来源于stack exchange,提问作者user21116899
相关产品推荐
相关产品推荐

