The events are very common in any web application and we need to test them as well, so let's learn how to test events. For this, let's create a new ShowInformation component:
import React, { Component } from 'react';
class ShowInformation extends Component {
state = {
name: '',
age: 0,
show: false
};
handleOnChange = ({ target: { value, name } }) => {
this.setState({
[name]: value
});
}
handleShowInformation = () => {
this.setState({
show: true
});
}
render() {
if (this.state.show) {
return (
<div className="ShowInformation">
<h1>Personal Information</h1>
<div className="personalInformation">
<p><strong>Name:</strong> {this.state.name}</p>
<p><strong>Age:</strong> {this.state.age}</p>
</div>
</div>
);
}
return (
<div className="ShowInformation">
<h1>Personal Information</h1>
<p><strong>Name:</strong></p>
<p>
<input
name="name"
type="text"
value={this.state.name}
onChange={this.handleOnChange}
/>
</p>
<p>
<input
name="age"
type="number"
value={this.state.age}
onChange={this.handleOnChange}
/>
</p>
<p>
<button onClick={this.handleShowInformation}>
Show Information
</button>
</p>
</div>
);
}
}
export default ShowInformation;
You will probably get the following error when you try to run this code:
To fix this issue, you need to install the following package:
npm install @babel/plugin-proposal-class-properties
And then you need to add it to your .babelrc file as a plugin:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": ["@babel/plugin-proposal-class-properties"]
}
Now, let's create the test file at src/components/ShowInformation/index.test.js:
// Dependencies
import React from 'react';
import { shallow } from 'enzyme';
// Component to test...
import ShowInformation from './index';
describe('ShowInformation', () => {
const wrapper = shallow(<ShowInformation />);
it('should render ShowInformation component', () => {
expect(wrapper.length).toBe(1);
});
it('should modify the state onChange', () => {
wrapper.find('input[name="name"]').simulate('change', {
target: {
name: 'name',
value: 'Carlos'
}
});
wrapper.find('input[name="age"]').simulate('change', {
target: {
name: 'age',
value: 31
}
});
// Getting the values of the name and age states
expect(wrapper.state('name')).toBe('Carlos');
expect(wrapper.state('age')).toBe(31);
});
it('should show the personal information when user clicks on the button', () => {
// Simulating the click event
wrapper.find('button').simulate('click');
// The show state should be true...
expect(wrapper.state('show')).toBe(true);
});
});
If you run the test and it works fine, you should see this: