【问题标题】:React Unit Testing Jest History PushReact 单元测试 Jest 历史推送
【发布时间】: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


    【解决方案1】:

    您可以使用useHistory 返回的history 对象中的goBack 方法。请看下面的示例,它是如何工作的,除了调用 {selector}.props().click() 之外,您还必须使用 enzyme 模拟点击事件。

    Example.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;
    

    示例.spec.jsx | Example.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');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多