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



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

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

react-hooks-testing-library的作者。

react-hooks-testing-library不是用于测试组件和询问内部钩子状态以断言其值,而是用于测试自定义 react 钩子并与钩子的结果进行交互以确保它的行为符合您的预期。 例如,如果要提取如下所示的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
});

相关内容

  • 没有找到相关文章

最新更新