Ankit Jain
Ankit Jain

Reputation: 333

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

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",

Upvotes: 2

Views: 1824

Answers (1)

Marek Rozmus
Marek Rozmus

Reputation: 958

Your "component" is an incorrect mock. You can try something like this:

test('should call function "OnChange"', () => {
  const mockSetState = jest.fn();
  const component = {
    setState: mockSetState,
    state: {
        name: "test",
    }
  };

  const event = {
    preventDefault() {},
    target: { name: "name", value: "the-value" },
  };

  OnChange(component, component.state, event);
  expect(mockSetState).toBeCalledWith({"name": "the-value"});
});

As far as I understand you are trying to check if setState method is called with proper arguments?

Upvotes: 2

Related Questions