首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试-库无法看到我的muiButton

测试-库无法看到我的muiButton
EN

Stack Overflow用户
提问于 2022-11-22 14:58:47
回答 1查看 11关注 0票数 1

我正在使用测试-库与MUI按钮。

我的测试:

代码语言:javascript
复制
  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输出:

代码语言:javascript
复制
 <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>

我的错误:

代码语言:javascript
复制
Error: Unable to fire a "click" event - please provide a DOM element.

如果我用

代码语言:javascript
复制
fireEvent.click(screen.getByText(/Afficher Plus/gi));

它工作得很好,所以我想"/gi“是在做些什么。但是我想使用queryByRole,因为它更干净。

EN

回答 1

Stack Overflow用户

发布于 2022-11-22 15:05:23

给您一个aria-label属性,例如aria-label="my-btn",所以在您的情况下:

代码语言:javascript
复制
<button
          class="MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeMedium MuiButton-textSizeMedium MuiButtonBase-root  css-1throlb-MuiButtonBase-root-MuiButton-root"
          tabindex="0"
          type="button"
          aria-label="my-btn"
        >

然后,在react测试库中,您可以使用getByRole并指定name属性来抓取按钮进行测试。

代码语言:javascript
复制
test("Valentin Garreau's btn ", () => {
                // first make sure react-testing-lib can find it
                expect(screen.getByRole('button', { name: 'my-btn' })).toBeVisible();

                // then test your stuff
                fireEvent.click(screen.getByRole('button', { name: 'my-btn' }));
                expect( <insert assertion here> )
            });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74534674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档