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.
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
Asked: 2023-05-13 11:34:46 +0000
Seen: 10 times
Last updated: May 13 '23
How can we update and display refreshed table data in React?
How can I display a loading message in aggrid using react js?
How can a component be utilized in both React and Angular?
What does BAD_AUTHENTICATION mean in React Native Authentication login?
How can I make useEffect wait for the state to update in React?
When using react, what appears on the user's browser?