0

I am trying to write a jest test for the functional component using enzyme. I am having a component inside that I am having a method which returns the jsx elements. Out of three elements two are dropdown elements. I need to write test for that two dropdown fields. I have tried various ways and approaches all got failed. I need to test the functionality of onChange and default value of that dropdown field.

React code :

const componentA = () => { 
   const [capStatus, setCapStatus] = useState(cap.status) // here cap is props I am setting it as default value as status in capStatus

  const handleStatus = (e) => {
    setCapStatus(e.target.value);

const devlopField = () => {
<SelectField
            id="mod-status"
            defaultValue={capStatus}
            onChange={handleStatus}
            required         
 >
            {
              cpdS.map(status => ( //cpdS is a constant file where I am having 4 different status 
                <SelectField.Option
                  value={status.type}
                  display={status.display}
                />
              ))
            }
          </SelectField>
}

JEST:

describe('StatusOnChange', () => {
  it('should have the correct default value and trigger onChange', () => {
    cap.status = 'Active';

    const statusWrapper = mount(CPV  cap={cap} />);
    const mockEvent = { target: { value: 'newStatus' } };
    statusWrapper.find('SelectField#modify-status-dropdown').props().onChange(mockEvent);
    expect(statusWrapper.find('CPV').props().capStatus).toBe('newStatus');
  });
});

For the above test in received I am getting undefined. I tried various approaches but nothing works. Anybody can let me know what am I missing in the test ? Thanks in advance!

I tried various methods the second method is

const defaultValue = 'Active';
  const updatedValue = 'Reject';
  cap.status = 'Active';

  const wrapper1 = mount(<CPV
    cap={cap}
  />);

  beforeEach(() => {
    jest.clearAllMocks();
    jest.resetAllMocks();
  });

  it('should update Status state on handleStatus', () => {
    const selectField = wrapper1.find('SelectField[id="mod-stat"]');

    expect(selectField.prop('defaultValue')).toBe(defaultValue);

    act(() => {
      selectField.prop('onChange')({ target: { value: updatedValue } });
    });

    wrapper1.update();
    const updatedStatusValue = wrapper1.find('cpd').props().cap.status;

    expect(updatedStatusValue).toBe(updatedValue);
  });
});

I need to test the default value first and after that I need to stimulate the onChange and capture the value which is changed with the help of handlefunction(handleStatus)`

Sunny
  • 708
  • 1
  • 4
  • 21
roshan26
  • 1
  • 2

0 Answers0