How to access Child component state and lifecycle methods and validate in React with Jest+Enzyme?

穿精又带淫゛_ 提交于 2019-12-13 00:35:51

问题


Need help with enzyme for testing. I have checked here but it did not help: How does one access state on a nested React component wrapped by an HOC?

Here is my problem:

How can I check function called or not and state of Child component? I also need to check lifecycle, so I used mount of parent component, but haven't done that yet. I used below when I rendered one component:

expect(searchWrapper.find('select [selected]').val()).to.equal('someId'),

but with mount, this is not working, as it complains searchWrapper.find(...).val is not a function which I believe is a cheer IO and it worked with render only. So what will be the proper way for me?

What I intend to do: On child select change, check (and/or match):

  1. child func is called once
  2. parent func is called once (called inside 1.)
  3. parent state
  4. child state
  5. lifecyle methods like componentWillReceiveProps and componentDidMount etc
  6. Result rendered output validation, also including some of the above.

Component is like

class ParentWrapper {
    // state and other functions and lifecycle methods
    render(){
        ....
        <SearchWrapper {...props}/>
        <ResultWrapper {...props}/>
    }
}

class SearchWrapper {
    // state
    // lifecycle methods
    // functions
}

and same for ResultWrapper.

Summarizing it again with some code: I want to access state and other objects of Child node, just like we can do with root. Also access rendered objects like selected option from the select menu, for example.

// state is not a function, as it has to be called for root only, then whats the alternative
expect(parentWrapper.find(SearchWrapper).state().searchId).to.equal('someValue');

// Below also did not work, it worked when I tested SearchWrapper individually using render() 
// which is a CheerIO function, but I need to use mount of parent for whole component testing 
// and inter-component interactions

searchWrapper.find('.form1 select').simulate('change', {target : {value : 'someValue'}});
// sinon spy on change is triggered

expect(searchWrapper.render().find('select [selected]').val()).to.equal('someValue');
// AssertionError: expected undefined to equal 'someValue'

来源:https://stackoverflow.com/questions/49487409/how-to-access-child-component-state-and-lifecycle-methods-and-validate-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!