【问题标题】:React testing: How can I reach the instance of a connected (redux) componentReact 测试:如何访问已连接(redux)组件的实例
【发布时间】:2017-08-08 15:57:37
【问题描述】:

我希望能够测试作为连接组件导出的组件的方法,因此我需要访问该组件的实例。

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

我无法到达那个实例。

【问题讨论】:

标签: reactjs unit-testing testing redux


【解决方案1】:

我采用的方法是为MyComponentmapStateToPropsmapDispatchToProps 创建单元测试。看起来MyComponent 的单元测试可以完成你想做的事情。

与 Redux 的集成测试有助于确定未来的升级是否会破坏您所依赖的功能,但您无需使用 Redux 完全启动您的应用程序来确定您的组件的方法是否按预期工作。

【讨论】:

    【解决方案2】:

    对您来说最简单的选择是导出未连接的组件,并创建测试,您可以在其中传递从商店获得的道具(基本上绕过 mapStateToProps)。

    另一个选项是为连接的组件创建一个测试。在这种情况下,您需要将它包装在一个Provider 中,并给它一个初始状态,以便它从存储本身获取信息。使用jest 执行此操作的助手的一个示例是:

    import React from 'react'
    import renderer from 'react-test-renderer'
    import { Provider } from 'react-redux'
    
    import configureMockStore from 'redux-mock-store'
    
    const fullRender = (jsx, state = {}) => {
      const store = configureMockStore([](state)
      const component = renderer.create(
        <Provider store={store}>
          {jsx}
        </Provider>
      )
    
      return { store, component }
    }
    export default fullRender
    

    这可以扩展为使用更真实的设置,例如在状态中包含中间件(例如 thunk)或同时考虑路由。然后你可以像这样构建你的测试(再次使用jest):

    import React from 'react'
    import { fullRender } from '../../test'
    import Header from './Header'
    
    describe('components', () => {
      let state = { a: { b: 3 } }
      describe('Header', () => {
        it('renders correctly', () => {
          const { component } = fullRender(<Header />, state)
          expect(component.toJSON()).toMatchSnapshot()
        })
      })
    })
    

    您可以将测试的“快照”存储为夹具,并将其提供给您的测试。

    【讨论】:

    • 感谢 Mario,但这是在测试组件的渲染,而不是到达它的实例。假设我需要测试类似: const componentInstance =
    • mhm 如果你想拥有一个可以手动运行其方法的组件,也许你可以使用enzyme 挂载它,尽管我不确定这是否被认为是一种好习惯
    猜你喜欢
    • 2017-03-29
    • 2017-11-26
    • 2016-12-24
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多