Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example of how you can test the handleChange event function in React 16 utilizing Jest and Enzyme:

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('calls handleChange on input change', () => {
    const wrapper = shallow(<MyComponent />);
    const mockFn = jest.fn();
    wrapper.instance().handleChange = mockFn;

    const event = {
      target: {
        name: 'myInput',
        value: 'myValue'
      }
    };
    wrapper.find('input[name="myInput"]').simulate('change', event);

    expect(mockFn).toHaveBeenCalledTimes(1);
    expect(mockFn).toHaveBeenCalledWith(event);
  });
});

In this example, we have a <MyComponent> component that has an <input> field with a name of "myInput". The handleChange function is defined in the component and is called when the <input> value changes.

To test this function, we first use shallow() from Enzyme to create a shallow rendering of the component. We then create a jest.fn() mock function and set it as the handleChange function on the component instance using wrapper.instance().handleChange = mockFn.

Next, we create a mock event object that simulates a change event with a target name of "myInput" and a value of "myValue". We then simulate the change event on the <input> field using wrapper.find('input[name="myInput"]').simulate('change', event).

Finally, we use expect() from Jest to test that the mock function mockFn was called once with the event object as its parameter.