DEV Community

S. M. Ahad Ali Chowdhury
S. M. Ahad Ali Chowdhury

Posted on

React js Input Field test using Jest and Enzyme

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'
      />
Enter fullscreen mode Exit fullscreen mode

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);
  };
Enter fullscreen mode Exit fullscreen mode

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");
  });
Enter fullscreen mode Exit fullscreen mode

here the explain

  1. 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.

  2. 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."

  3. 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.

  4. 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.

  5. 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)