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

使用Testing-Library时queryByRole无法定位MUI Button的问题求助

问题:Testing-Library使用queryByRole定位MUI Button失败

我在用Testing-Library测试MUI Button时遇到问题,测试代码如下:

it('Should show more when I click on show more', () => {
  render(<RankedThemes {...props} />);
  expect(screen.getAllByText(/^citations positives$/)).toHaveLength(3);

  fireEvent.click(screen.queryByRole('button', { name: 'Afficher Plus'}));
  expect(screen.getAllByText(/^citations positives$/)).toHaveLength(topPositive.length);
});

对应的页面HTML输出:

<div
        class="MuiGrid-root MuiGrid-container css-1hbmzt3-MuiGrid-root"
      >
        <button
          class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root  css-1throlb-MuiButtonBase-root-MuiButton-root"
          tabindex="0"
          type="button"
        >
          <div>
            <svg
              aria-hidden="true"
              class="MuiSvgIcon-root MuiSvgIcon-fontSizeMedium css-i4bv87-MuiSvgIcon-root"
              data-testid="KeyboardArrowDownIcon"
              focusable="false"
              viewBox="0 0 24 24"
            >
              <path
                d="M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"
              />
            </svg>
             
            Afficher plus
          </div>
          <span
            class="MuiTouchRipple-root css-8je8zh-MuiTouchRipple-root"
          />
        </button>
      </div>

执行测试时触发错误:

Error: Unable to fire a "click" event - please provide a DOM element.

使用fireEvent.click(screen.getByText(/Afficher Plus/gi))可以正常运行,但希望通过更规范的queryByRole方法解决问题。


解决方案

  • 修正文本大小写匹配:HTML中按钮实际文本是Afficher plus(小写p),而测试代码里写的是Afficher Plus(大写P),大小写不匹配导致queryByRole无法定位元素。可以直接修改name值为Afficher plus,或者用正则忽略大小写:
    screen.queryByRole('button', { name: /Afficher Plus/gi })
    
  • 选择更合适的查询方法:如果按钮在页面中必然存在,推荐用getByRole替代queryByRole——getByRole会在找不到元素时直接抛出明确的错误信息,便于调试,而queryByRole返回null才导致后续点击操作报错。调整后的测试代码:
    fireEvent.click(screen.getByRole('button', { name: /Afficher plus/i }));
    
  • 理解可访问名称匹配逻辑:Testing-Library的name参数匹配的是元素的可访问名称,这里按钮内部包含图标和文本,使用正则表达式能更灵活地匹配目标内容,避免因空格或额外元素干扰匹配结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:01:25