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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:06:17