How To Test Parent Passing `this` To Children Using Enzyme
I have below code where Parent
Component is passing it's this
to Child
Component. Child
Component will do some work and then do setState
in Parent
Component.
How Should i go about testing only Child Component. Means how can i create dummy Parent
and later on check value in it's state using enzyme
& jest
.
class Parent extends React.Component {
constructor(props) {
super(props);
this.state={
status: '',
}
}
render(){
return (
<div>
<Child
parentThis={this}
/>
</div>
);
}
}
class Child extends React.Component {
doSomeWork = () => {
const {parentThis} = this.props;
parentThis.setState({
'status': '1'
})
}
render() {
this.doSomeWork()
return (<div></div>);
}
}
I want to do Unit testing of Child
Component. I want to make sure that Child
is correctly updating state
of Parent
Component.
Answer
Well,
I have below code where Parent Component is passing it's this to Child Component. Child Component will do some work and then do setState in Parent Component.
Don't do that. That is never a good pattern for testing purposes - and neither a good pattern in React.
React allows you to pass functions to components, in your case a callback. So instead of passing this
, pass a function onChangeStatus
. A full example might look like the following:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state={
status: '',
}
}
render(){
return (
<div>
<Child onChangeStatus={(status) => this.setState({status})}
status={this.state.status}
/>
</div>
);
}
}
class Child extends React.Component {
doSomeWork = () => {
const {onChangeStatus} = this.props;
onChangeStatus({
status: '1'
})
}
render() {
this.doSomeWork()
return (<div></div>);
}
}
To test it, just test if a function you pass to the child gets called. I seldom use enzyme, but this article looks promising on how to test the function.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?