【发布时间】:2021-09-06 05:24:34
【问题描述】:
我得到了我需要测试的这个方法。我试图嘲笑历史,但我无法让它发挥作用。我只想检查是否有一个 Button,如果我点击它,应该处理 DrawerToggle 并推回 Path。
imports...
export const SettingsSidebar = ({ listItems }) => {
const gobackPath = (history.location.state as any)?.gobackPath;
some methods...
return (
...some other Codes
<DrawerMenu>
<GoBackButtonLg onClick={() => history.push(gobackPath)}>Zurück zum Workspace</GoBackButtonLg>
<SidebarList>
<SidebarListItem
goBackButton
button
key={'goback'}
icon={<GoBackButtonSm icon={faChevronLeft} />}
onClick={() => handleMenuClick(gobackPath)}
>
Zurück zum Workspace
</SidebarListItem>
{listItems.map(res => (
<SidebarListItem
button
key={res.name}
icon={<FontAwesomeIcon icon={res.icon} />}
onClick={() => handleMenuClick(res.path)}
>
{res.name}
</SidebarListItem>
))}
</SidebarList>
</DrawerMenu>
and so on...
);
};
export default SettingsSidebar;
测试:
imports...
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
useHistory: () => ({ push: mockHistoryPush }),
}));
describe('SettingsSidebar', () => {
const mockHandleDrawerToggle = jest.fn();
beforeAll(() => {
configure({ adapter: new Adapter() });
});
it('should have a button', () => {
const wrapper = shallow(<SettingsSidebar listItems/>);
const button = wrapper.find(GoBackButton);
button.props().onClick();
expect(mockHandleDrawerToggle).toHaveBeenCalledTimes(1);
});
});
失败的消息
【问题讨论】:
标签: javascript unit-testing jestjs mocking history