How to test onChange for ui-material TextField using Jest and Enzyme

Viewed 1952

I am new to testing, I cannot figure out how to test the changing value in the TextField component

   export const ParentComponent = ({
    question,
    onValueChange
    }: ParentProps) => {

    const [value, setValue] = useState(default);

    const onChange = event => {
    const answer = event.target.value;
    setValue(answer);
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      onValueChange(question);
     }, 500);
    };

return (
    <TextField
      className={classes.textField}
      InputLabelProps={{
        className: classes.color
      }}
      onChange={onChange}
      value={value || ""}
    />);
   };

This is what I have so far from other answers I read, not sure how to handle the difference between onValueChange and onChange:

describe("ParentComponent", () => {
  let mount;
   
  beforeEach(() => {
    mount = createMount();
  });
  afterEach(() => {
    mount.cleanUp();
  });
  it("renders", () => {
    const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
    expect(wrapper).not.toBeNull();
  });



 it("Should change value when text is entered", () => {
        const onChange = jest.fn();
        const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
        const event = {
          target: {
            value: "This is just for test"
          }
        };
        wrapper.find(TextField).simulate("change", event);
        expect(onChange).toHaveBeenCalled();
        expect(onChange).toHaveBeenCalledWith("This is just for test");
      });

Getting this error:

Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls:    0
1 Answers

First, you have to spy on the onChange function:

const onChange = jest.spyOn(TextField.prototype, 'onChange');

@material-ui provides complex components, so I guess you'd test it like this (also note that enzyme's find() returns a collection of nodes):

wrapper.find(TextField).find('input').at(0).simulate('change', event);
Related