【问题标题】:How to test Reach UI Menu Button with react testing library如何使用反应测试库测试到达 UI 菜单按钮
【发布时间】:2022-01-19 21:56:22
【问题描述】:

在测试到达 UI 菜单按钮时,它显示为通过 RTL 无法单击通过反应门户显示的菜单项。调用userEvent.click时可以找到元素但没有触发任何事件。

我有一个最小的repo here 重现该问题。

【问题讨论】:

    标签: reactjs unit-testing react-hooks react-testing-library


    【解决方案1】:

    test case source code 开始,MenuItem 组件的onSelect 事件处理程序将由以下辅助函数触发:

    function simulateSpaceKeyClick(element, opts) {
      let { fireClick } = opts || {};
      fireEvent.keyDown(element, { key: " " });
      fireEvent.keyUp(element, { key: " " });
      if (fireClick) {
        fireEvent.click(element);
      }
    }
    

    userEvent.click 不起作用。

    完整示例:

    menu.js:

    import React, { useState, Fragment } from "react";
    import {
      Menu,
      MenuList,
      MenuButton,
      MenuItem,
      MenuLink
    } from "@reach/menu-button";
    
    export default function () {
      const [isDownloading, setIsDownloading] = useState(false);
      return (
        <Fragment>
          <Menu>
            <MenuButton data-testid="action-button">
              Actions <span aria-hidden>▾</span>
            </MenuButton>
            <MenuList>
              <MenuItem
                data-testid="action-button-download"
                onSelect={() => {
                  console.log("?");
                  setIsDownloading(true);
                }}
              >
                Download
              </MenuItem>
              <MenuLink as="a" href="https://reach.tech/workshops">
                Attend a Workshop
              </MenuLink>
            </MenuList>
          </Menu>
          {isDownloading && <p data-testid="downloading">Downloading...</p>}
        </Fragment>
      );
    }
    

    menu.spec.js:

    import React from "react";
    import { render, screen, fireEvent } from "@testing-library/react";
    
    import Menu from "../menu";
    
    function simulateSpaceKeyClick(element, opts) {
      let { fireClick } = opts || {};
      fireEvent.keyDown(element, { key: " " });
      fireEvent.keyUp(element, { key: " " });
      if (fireClick) {
        fireEvent.click(element);
      }
    }
    
    test("should be able to click a menu item when open", async () => {
      render(<Menu />);
    
      simulateSpaceKeyClick(screen.getByText(/actions/i));
      expect(screen.getByText(/download/i)).toBeTruthy();
      simulateSpaceKeyClick(screen.getByText(/download/i));
      expect(await screen.findByTestId("downloading")).toBeTruthy();
    });
    

    codesandbox

    【讨论】:

    • 感谢您的回答,这部分有效,因为它目前依赖于列表中的第一个“下载”项目,因为它由库自动聚焦 fireEvent.mouseEnter(element); 在函数中也是必需的处理列表中的任何项目。你知道为什么 userEvent.click 不起作用它看起来像 onClick 仍然绑定到元素
    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2021-05-09
    • 2020-07-07
    • 1970-01-01
    • 2022-06-21
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多