Ask Your Question
3

What is the method for testing the handleChange event function in react 16 utilizing jest and Enzyme?

asked 2023-05-13 11:34:46 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-13 11:35:01 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-13 11:34:46 +0000

Seen: 10 times

Last updated: May 13 '23