【问题标题】:How to test a React component that has Router, Redux and two HOCs... with Jest and Enzyme?如何使用 Jest 和 Enzyme 测试具有 Router、Redux 和两个 HOC 的 React 组件?
【发布时间】:2018-10-21 10:38:56
【问题描述】:

我目前无法找到解决此问题的方法。 我有一个 React 组件,它连接到 React Router 4、Redux 存储并由两个 HOC 包装。它非常疯狂,但这就是它的编码方式。 这是给你一个想法的出口:

export default withFetch(Component)(fetchData, mapStateToProps)

我正在尝试对其进行一些基本测试:

  it('should render self and subcomponents', () => {
    const wrapper = shallow(<Component {...props} />)
    expect(toJson(wrapper)).toMatchSnapshot()
  })

输出如下的console.log/snapshot:

<Route render={[Function: render]} />

尝试了但没有成功:

  1. 我尝试将我的组件包装在 Memory Router
  2. 为组件提供一个 redux store
  3. 使用.dive().chilndren() 尝试看孩子
  4. 尝试mountrender 均未成功。

仍然不断渲染&lt;Route render={[Function: render]} /&gt;

试用:

<MemoryRouter>
    <Component {...props} />
</MemoryRouter>

仍然产生相同的结果。 请注意,我也尝试将我的组件导入为

import { Component } from './components/'

但它返回未定义。

非常感谢任何帮助。谢谢! ??????????

【问题讨论】:

    标签: javascript reactjs redux jestjs enzyme


    【解决方案1】:

    我假设&lt;Router&gt; 你指的是BrowserRouter。 最好的方法是隔离封装的组件并使用测试替代方案对其进行测试。

    例如假设您要测试:

    // App.jsx
    
    export const App = () => 
    <Router>
      <ReduxProvider>
         <AppInner>
      </ReduxProvider>
    </Router>
    

    我的建议是使用 Router 和 ReduxProvider 的测试环境来测试 AppInner

    在测试中:

    // AppInner.test.jsx
    
    import {mount} from 'enzyme';
    import {MemoryRouter} from 'react-router';
    describe('AppInner', () => {
       it('should do something', () => {
          const TestingComponent = () =>
          <MemoryRouter>
             <ReduxProvider>
                <AppInner />
             <ReduxProvider>
          <MemoryRouter>;
          const component = mount(TestingComponent);
       });
    })
    

    注意我已经用MemoryRouter 包裹了AppInner,它允许你的模拟路由器但不依赖于浏览器。

    有关更多信息,您可以阅读react-routertesting 部分;

    【讨论】:

    • 请注意 mount 完全改变了输出!我使用的是 Shallow。
    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 2017-11-10
    • 2018-11-04
    • 2017-04-13
    • 2019-01-27
    • 2020-04-08
    • 2019-02-20
    • 2021-06-24
    相关资源
    最近更新 更多