1

我导航组件然后将在侧边栏中切换状态以及打开和关闭菜单,然后尝试在代码覆盖范围内获得此通过。当我登录我的测试时,我的状态一直显示为未定义。不知道如何在这里解决这个问题。

组件.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;

测试.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();
});
4

1 回答 1

5

这里的作者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();
});

不过,一般来说,当一个钩子仅由单个组件和/或在单个上下文中使用时,我们建议您简单地测试该组件并允许通过它测试该钩子。

为了测试你的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
});
于 2020-01-30T10:27:07.213 回答