testing the input field with jest and enzyme
first take a input field in your react js file like this
<input
type="text"
value={inputValue}
onChange={handleChange}
className='inputfield'
/>
for this input field, take handleChange function , and a useState for the input Value , like this
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
this take the input from the user,
Now here, i want write test file for this input field,
it('updates input value on change', () => {
const wrapper = shallow(<App />);
const input = wrapper.find('.inputfield');
input.simulate('change', { target: { value: 'ahad' } });
const refoundInput = wrapper.find(".inputfield")
expect(refoundInput.props().value).toEqual("ahad");
});
here the explain
const wrapper = shallow(<App />);
It starts by shallow rendering the App component, which means it renders the component without rendering its children or diving deep into the component tree. This allows you to isolate your testing to the behavior of the App component itself.const input = wrapper.find('.inputfield');
It finds an input element with a CSS class of "inputfield" within the rendered App component. This is assuming that your input field has a class attribute set to "inputfield."input.simulate('change', { target: { value: 'ahad' } });
It simulates a change event on the found input field and sets its value to 'ahad'. This simulates a user typing 'ahad' into the input field.const refoundInput = wrapper.find(".inputfield");
It finds the input element again after the simulated change event. This step is necessary because the input variable from step 2 may not reflect the updated state of the input field after the simulated change event.expect(refoundInput.props().value).toEqual("ahad");
It uses an assertion to check whether the value prop of the input field, which was found again in step 4, is equal to 'ahad'. This ensures that the input field's value has been updated correctly in response to the simulated change event.
Top comments (0)