简体   繁体   English

如何使用带有钩子的反应功能组件测试句柄 function 调用

[英]How to test a handle function call with a react functional component with hooks

I'm trying to write unit tests for a fairly simple tab bar I made with Material ui.我正在尝试为我用 Material ui 制作的一个相当简单的标签栏编写单元测试。

Basically I just want to test whether or not the handleTabChange function was called when a tab was clicked, and that the right value was passed in. I also wanted to test if the routing worked, ie if testing the 'Feed' button took you to /feed but I couldn't get that to work either.基本上我只想测试在单击选项卡时是否调用了handleTabChange function,并且传入了正确的值。我还想测试路由是否有效,即测试“Feed”按钮是否将您带到/feed但我也无法让它工作。

TabBar.jsx标签栏.jsx

 import React, { useState } from 'react'; import { Tabs, Tab } from '@material-ui/core'; import { withRouter } from 'react-router-dom'; import { object } from 'prop-types'; import { tabToPathnameMap, pathnameToTabMap } from '../../constants/constants'; const TabBar = (props) => { const { history, location } = props; const { pathname } = location; const handleTabChange = (e, newValue) => { setCurrentTab(newValue); history.push(tabToPathnameMap[newValue]); }; const [currentTab, setCurrentTab] = useState( pathnameToTabMap[pathname]? pathnameToTabMap[pathname]: false ); return ( <Tabs value={currentTab} onChange={(e, newValue) => handleTabChange(e, newValue)} centered > <Tab label="Feed" tabBar-tab-testId="Feed" /> <Tab label="Fork" tabBar-tab-testId="Fork" /> <Tab label="Favs" tabBar-tab-testId="Favs" /> </Tabs> ); }; TabBar.propTypes = { history: object, location: object }; export default withRouter(TabBar);

TabBar.test.jsx TabBar.test.jsx

 import React from 'react'; import { mount } from 'enzyme'; import { MemoryRouter } from 'react-router-dom'; import TestComponentWrapper from '../../TestComponentWrapper'; import TabBar from '../../../Components/TabBar/TabBar'; describe('TabBar', () => { it('should move to /fork when the fork tab is clicked', () => { const wrapper = mount( <TestComponentWrapper> <MemoryRouter initialEntries={['/']}> <TabBar /> </MemoryRouter> </TestComponentWrapper> ); const spy = jest.spyOn(wrapper.instance(), 'handleTabChange'); expect(spy).toHaveBeenCalledTimes(0); wrapper.find('[tabBar-tab-testId="Fork"]').hostNodes().simulate('click'); expect(spy).toHaveBeenCalledTimes(1); }); });

Right now I'm getting an error that wrapper.instance() returns null - and I have just learned that you can't use it with stateless functional components.现在我收到一个错误,即wrapper.instance()返回 null - 我刚刚了解到您不能将它与无状态功能组件一起使用。

Does anyone know how I can test the function / and or the that the path changes when I click on one of these tabs?有谁知道我如何测试 function / 或者当我单击这些选项卡之一时路径会发生变化?

I think you should export named constant along with your default export.我认为您应该将命名常量与默认导出一起导出。

import React, { useState } from 'react';
import { Tabs, Tab } from '@material-ui/core';
import { withRouter } from 'react-router-dom';
import { object } from 'prop-types';
import { tabToPathnameMap, pathnameToTabMap } from '../../constants/constants';

//CHANGED THIS LINE
export const TabBar = (props) => {
  const { history, location } = props;
  const { pathname } = location;

  const handleTabChange = (e, newValue) => {
    setCurrentTab(newValue);
    history.push(tabToPathnameMap[newValue]);
  };

  const [currentTab, setCurrentTab] = useState(
    pathnameToTabMap[pathname] ? pathnameToTabMap[pathname] : false
  );

  return (
    <Tabs
      value={currentTab}
      onChange={(e, newValue) => handleTabChange(e, newValue)}
      centered
    >
      <Tab label="Feed" tabBar-tab-testId="Feed" />
      <Tab label="Fork" tabBar-tab-testId="Fork" />
      <Tab label="Favs" tabBar-tab-testId="Favs" />
    </Tabs>
  );
};

TabBar.propTypes = {
  history: object,
  location: object
};

export default withRouter(TabBar);

And then in your test, import the named constant instead of the default.然后在您的测试中,导入命名常量而不是默认值。

import React from 'react';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import TestComponentWrapper from '../../TestComponentWrapper';
//CHANGED THIS LINE
import { TabBar } from '../../../Components/TabBar/TabBar';

describe('TabBar', () => {
  it('should move to /fork when the fork tab is clicked', () => {
    const wrapper = mount(
      <TestComponentWrapper>
        <MemoryRouter initialEntries={['/']}>
          <TabBar />
        </MemoryRouter>
      </TestComponentWrapper>
    );
    const spy = jest.spyOn(wrapper.instance(), 'handleTabChange');
    expect(spy).toHaveBeenCalledTimes(0);
    wrapper.find('[tabBar-tab-testId="Fork"]').hostNodes().simulate('click');
    expect(spy).toHaveBeenCalledTimes(1);
  });
});

Didn't test it, but it should work.没有测试它,但它应该工作。

暂无
暂无

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

相关问题 如何测试反应功能组件异步调用 - How to test react functional component async call Function 在 React 钩子中的功能组件内 - 性能 - Function inside functional component in React hooks - Performance React 16:使用钩子和功能组件时,从父级调用子级的 function - React 16: Call children's function from parent when using hooks and functional component 如何在功能组件(React,React Hooks)中触发 function 后触发第二个 function - How to fire a second function after a triggering a function in a functional component (React, React Hooks) 收到此错误“无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。” 在反应功能组件内? - Getting this error “Invalid hook call. Hooks can only be called inside of the body of a function component.” inside a react functional component? 如何将 React class 组件转换为带有钩子的功能组件 - How to convert React class component to functional component with hooks 我如何调用/执行外部功能组件的 function 反应? - How can i call/execute function of functional component outside react? 如何在功能性 React 组件中修改 function 调用中的变量 - How to modify variable in function call in functional React component 从兄弟组件 React hooks 调用 function - Call function from sibling component React hooks 挂钩的调用在功能组件内部给出错误挂钩只能在 function 组件的主体内部调用 - Call of hooks is inside of functional component give error Hooks can only be called inside of the body of a function component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM