I want to write a test that checks the state of a parent component, after a button click in child component. Im trying to test for state of Toggled becoming true after a button click in Alameda component.
App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
Toggled: false
};
}
clickedbutton() {
this.setState(prevState => ({
Toggled: !prevState.Toggled
}));
}
render() {
return (
<div>
<header>
<h1>App Component</h1>
</header>
<Alameda clickedbutton={this.clickedbutton} />
</div>
);
}
}
Alameda.js
class Alameda extends Component {
render() {
return (
<div>
<button onClick={this.props.clickedbutton}>
</button>
</div>
);
}
}
App.test.js
it('check parent components state with button click', () => {
const wrapper = shallow(<App />);
const wrap = shallow(<Min />);
const minButton = wrap.find('button');
minButton.find('button').simulate('click');
expect(wrapper.state().Toggled).to.equal(true);
})
I cant get seem to get the state of Toggled to equal true. It stays at false. Can anybody help?
Looks there are a couple issues here.
One is that you are creating two wrappers - wrapper
and wrap
. Each wrapper is a separate React component tree so simulating the click in wrap
will change nothing in wrapper
. You should create one wrapper per test to simulate, find and assert what you want.
The other problem is your approach to finding the button is not possible with shallow
rendering. I recommend you use mount and spend some time learning about the difference between the rendering methods. The debug
method is useful for figuring out what is rendered in wrapper. Try printing stuff like shallow(<App />).debug()
and mount(<App />).debug()
.
If you decide to use mount
, the following test should work:
it('check parent components state with button click', () => {
const wrapper = mount(<App />);
const minButton = wrapper.find('button');
minButton.find('button').simulate('click');
expect(wrapper.state().Toggled).to.equal(true);
})
Thank you petegleeson!
Most helpful comment
Looks there are a couple issues here.
One is that you are creating two wrappers -
wrapper
andwrap
. Each wrapper is a separate React component tree so simulating the click inwrap
will change nothing inwrapper
. You should create one wrapper per test to simulate, find and assert what you want.The other problem is your approach to finding the button is not possible with
shallow
rendering. I recommend you use mount and spend some time learning about the difference between the rendering methods. Thedebug
method is useful for figuring out what is rendered in wrapper. Try printing stuff likeshallow(<App />).debug()
andmount(<App />).debug()
.If you decide to use
mount
, the following test should work: