How does one access state on a nested React component wrapped by an HOC?

后端 未结 2 1736
北荒
北荒 2020-12-14 18:47

I\'m using Enzyme, and we can actually use the example component given in the docs as a foundation for my question.

Let\'s assume this com

相关标签:
2条回答
  • 2020-12-14 19:07

    Thought it might be useful for you guys, as I stumbled upon this and have a fix.

    In my case I have a component which is connected to redux.

    class ComponentName extends Component {
    ...
    }
    export default connect(
      mapStateToProps,
      {
    ...
     }
    )(ComponentName );
    

    connect() is obviously a HOC component. So how do we access the "ComponentName" here?

    Very simple:

    component
        .find(ComponentName)
        .children()
        .first()
        .props() // returns ComponentName's props 
    
    0 讨论(0)
  • 2020-12-14 19:09

    So it seems with the latest release of Enzyme there is a potential fix for this issue of accessing state on a child component.

    Let's say we have <Foo> (note the use of React Router's <Link>)

    class Foo extends Component {
      state = {
        bar: 'here is the state!'
      }
    
      render () {
        return (
          <Link to='/'>Here is a link</Link>
        )
      }
    }
    

    Note: The following code is only available in Enzyme v3.

    Revisiting the test code, we are now able to write the following

    it('puts the lotion in the basket', () => {
      const wrapper = mount(
        <MemoryRouter>
          <Foo />
        </MemoryRouter>
      )
    
      expect(wrapper.find(Foo).instance().state).toEqual({
        bar: 'here is the state!'
      })
    })
    

    Using wrapper.find(Child).instance() we are able to access Child's state even though it is a nested component. In previous Enzyme versions we could only access instance on the root. You can also call the setState function on the Child wrapper as well!

    We can use a similar pattern with our shallowly rendered tests

    it('puts the lotion in the basket shallowly', () => {
      const wrapper = shallow(
        <MemoryRouter>
          <Foo />
        </MemoryRouter>
      )
    
      expect(wrapper.find(Foo).dive().instance().state).toEqual({
        bar: 'here is the state!'
      })
    })
    

    Note the use of dive in the shallow test, which can be run on a single, non-DOM node, and will return the node, shallow-rendered.


    Refs:

    • https://github.com/airbnb/enzyme/issues/361
    • https://github.com/airbnb/enzyme/issues/1289
    • https://github.com/airbnb/enzyme/blob/master/docs/guides/migration-from-2-to-3
    0 讨论(0)
提交回复
热议问题