使用 Jest 和 React Hooks 库测试 React Hooks 状态

Test react hooks state using Jest and React Hooks Library

I nav 组件然后将在侧边栏中切换状态以及打开和关闭菜单,然后尝试在代码覆盖率中获取此传递。当我登录我的测试时,我的状态一直显示为未定义。不知道如何解决这个问题。

Component.js:

const Navigation = (props) => {
  const {
    classes,
    ...navProps
  } = props;

  const [anchorEl, setanchorEl] = useState(null);
  const [sidebarOpen, setsidebarOpen] = useState(false);

  const toggleSidebar = () => {
    setsidebarOpen(!sidebarOpen);
  };

  const toggleMenuClose = () => {
    setanchorEl(null);
  };

  const toggleMenuOpen = (event) => {
    setanchorEl(event.currentTarget);
  };

  return (
    <Fragment>
     <Button
          onClick={toggleMenuOpen}
        />
      <SideMenu
        toggleSidebar={toggleSidebar}
      >
       <Menu
          onClose={toggleMenuClose}
        >
      </SideMenu>
    </Fragment>
  );
};

export default Navigation;

Test.js:

import { renderHook, act } from '@testing-library/react-hooks';

// Components
import Navigation from './navigation';

test('sidebar should be closed by default', () => {
    const newProps = {
        valid: true,
        classes: {}
    };

    const { result } = renderHook(() => Navigation({ ...newProps }));
    expect(result.current.sidebarOpen).toBeFalsy();
});

react-hooks-testing-library 的作者在这里。

react-hooks-testing-library 不是用于测试组件和询问内部钩子状态以断言它们的值,而是用于测试自定义反应钩子并与钩子的结果交互以确保它的行为符合您的预期。例如,如果你想提取一个看起来像这样的 useMenuToggle 钩子:

export function useMenuToggle() {
  const [anchorEl, setanchorEl] = useState(null);
  const [sidebarOpen, setsidebarOpen] = useState(false);

  const toggleSidebar = () => {
    setsidebarOpen(!sidebarOpen);
  };

  const toggleMenuClose = () => {
    setanchorEl(null);
  };

  const toggleMenuOpen = (event) => {
    setanchorEl(event.currentTarget);
  };

  return {
    sidebarOpen,
    toggleSidebar,
    toggleMenuClose,
    toggleMenuOpen
  }
}

然后你可以用 renderHook:

来测试它
import { renderHook, act } from '@testing-library/react-hooks';

// Hooks
import { useMenuToggle } from './navigation';

test('sidebar should be closed by default', () => {
    const newProps = {
        valid: true,
        classes: {}
    };

    const { result } = renderHook(() => useMenuToggle());
    expect(result.current.sidebarOpen).toBeFalsy();

    act(() => {
        result.current.toggleSidebar()
    })

    expect(result.current.sidebarOpen).toBeTruthy();
});

但一般来说,当挂钩仅由单个组件 and/or 在单个上下文中使用时,我们建议您只测试该组件并允许挂钩通过它进行测试。

要测试您的 Navigation 组件,您应该查看 react-testing-library

import React from 'react';
import { render } from '@testing-library/react';

// Components
import Navigation from './navigation';

test('sidebar should be closed by default', () => {
    const newProps = {
        valid: true,
        classes: {}
    };

    const { getByText } = render(<Navigation {...newProps} />);
    
    // the rest of the test
});