[Jest Unit Testing]: TypeError: component.setState is not a function

Viewed 18

We are using Jest for Unit Testing. We have a common file that contains the common OnChange() function definition. While writing unit test case for OnChange, it's throwing below error:

enter image description here

e.g.

CommonFunctions.tsx

export const OnChange = (component: any, property: any, event: any) => {
  property[event.target.name] = event.target.value;
  component.setState({
    ...component.state,
  });
};

Calling for OnChange from a class Component:

this.onChangeHandler = (event: any) => OnChange(this, this.state, event);

Jest Unit Test Case for OnChange: CommonFunctions.test.tsx

test('should call function "OnChange"', () => {
const property = {
  name: 'test',
};
const component = jest.fn();
const event = {
    preventDefault() {},
    target: { name: 'name', value: 'the-value' }
  };
expect(OnChange(component,property,event)).toBeCalledWith('the-value');

});

Please suggest a better or newer approach for this use case.

Versions: "react": "^18.1.0", "react-dom": "^18.1.0", "jest": "^29.0.3",

0 Answers
Related