繁体   English   中英

React 单元测试 Jest 历史推送

[英]React Unit Testing Jest History Push

我得到了这个我需要测试的方法。 我试图嘲笑历史,但我无法让它发挥作用。 我只想检查是否有一个按钮,如果我点击它,应该处理 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);
    });
  });

失败的消息

在此处输入图片说明

您可以从useHistory返回的history对象中使用goBack方法。 下面看看这是如何工作的一个例子,也而不是调用{selector}.props().click()你必须模拟与click事件enzyme

例子.jsx

import React from "react";
import { MemoryRouter, useHistory } from "react-router-dom";

export const ExampleComponent = () => {
    const history = useHistory();

    return (
        <div>
            <button
                data-testid="btn-go-back"
                onClick={() => history.goBack()}
            ></button>
            <button
                data-testid="btn-go-to-some-path"
                onClick={() => history.push("/to-some-path")}
            ></button>
        </div>
    );
};

export default ExampleComponent;

Example.spec.jsx | 示例.test.jsx

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ReactRouterDOM from 'react-router-dom';
import ExampleComponent from './Example';

configure({ adapter: new Adapter() });

const mockHistoryPush = jest.fn();
const mockHistoryGoBack = jest.fn();

jest.mock('react-router-dom', () => ({
    ...(jest.requireActual('react-router-dom'),
    useHistory: () => ({
        push: mockHistoryPush,
        goBack: mockHistoryGoBack,
    }),
}));

describe('Example', () => {
    afterEach(() => {
        jest.clearAllMocks();
    });

    it('invokes the history go back function when the go back button is clicked by the user', () => {
        const wrapper = shallow(<ExampleComponent />);
        const btn = wrapper.find("[data-testid='btn-go-back']");
        btn.simulate('click');
        expect(mockHistoryGoBack).toBeCalled();
    });

    it('invokes the history push function when the go back button is clicked by the user', async () => {
        const wrapper = shallow(<ExampleComponent />);
        const btn = await wrapper.find('[data-testid="btn-go-to-some-path"]')
        btn.simulate('click');
        expect(mockHistoryPush).toBeCalledWith('/to-some-path');
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM