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

如何为MaterialTable搜索框编写单元测试?元素定位问题求助

MaterialTable搜索框单元测试定位问题

我正尝试为MaterialTable的搜索框编写单元测试,但无法为该输入元素添加test-id。使用getByRole("input")定位输入元素时,出现错误“Unable to find an element by [role=input]”;使用getElementsByClassName定位也未成功。

我的测试代码如下:

test("should show the results properly after searching something", async () => {
    const selectedRowId = "DRQ000000000001";
    const lastDrawnRow = testDataRequests[0];
    const updateSelectedRow = jest.fn();

    const updateLastSelectedRow = jest.fn();
    const wrapper = render(
      <HistoricalDataSets
        testDataRequests={testDataRequests}
        selectedRowId={selectedRowId}
        lastDrawnRow={lastDrawnRow}
        updateSelectedRow={updateSelectedRow}
        updateLastSelectedRow={updateLastSelectedRow}
      />
    );
    const inputField = wrapper.getByRole("input");
    const searchText = "Fibre";
    fireEvent.change(inputField, { target: { searchText } });

    expect(wrapper.queryAllByText(/Fibre/)).toBeDefined();
    expect(wrapper.getAllByTestId("status-link").length).toBe(1);
  });

附渲染后的HTML截图(搜索框相关DOM结构)


解决方法

  1. 修正getByRole的参数
    输入元素的标准ARIA role是textbox而非input,结合搜索框的名称/占位符文本定位更准确:
const inputField = wrapper.getByRole("textbox", { name: /search/i });

name参数可匹配搜索框的标签、占位符或aria-label,根据实际DOM结构调整。

  1. 通过占位符直接定位
    如果搜索框有明确的占位符(比如“搜索...”),用getByPlaceholderText更直接:
const inputField = wrapper.getByPlaceholderText(/搜索/i); // 英文场景用/search/i
  1. 给搜索框添加自定义test-id
    MaterialTable支持通过options配置传递搜索框的属性,直接添加test-id:
// 在HistoricalDataSets组件内的MaterialTable配置中
<MaterialTable
  options={{
    searchFieldProps: {
      "data-testid": "table-search-input"
    }
  }}
  // 其他组件props
/>

之后测试中就能直接用test-id定位:

const inputField = wrapper.getByTestId("table-search-input");
  1. 修正事件触发的参数
    你当前的fireEvent.change参数错误,应该用value而非searchText来设置输入值:
fireEvent.change(inputField, { target: { value: searchText } });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:53:10