8

I'm currently testing an input using Jest & react-testing-library. I'm trying to test whether the onChange function fires whenever my input's field changes. Here's an example of my code:

const placeHolder = 'first name';
const onChange = jest.fn();

test('<InputText/>', () => {

  const {getByPlaceholderText} = render(
    <InputText placeholder={placeHolder} onChange={onChange} />
  );

  const input = getByPlaceholderText(placeHolder);

  fireEvent.change(input, {
    target: {value: 'pls work'},
  });

  expect(onChange).toHaveBeenCalledTimes(1);
});

Here's what a get in the terminal when I run this test:

expect(jest.fn()).toHaveBeenCalledTimes(1)

Expected mock function to have been called one time, but it was called zero times.

I've used the fireEvent.click() function in other tests without any issues yet, but fireEvent.change() doesn't seem to be working for me.

1

2 Answers 2

5

It turns out that my <InputText/> component takes in a onChangeFunc prop, while I was trying to give it a regular onChange prop. Once I realized that and gave it the correct prop, it fixed the issue.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of calling this

expect(onChange).toHaveBeenCalledTimes(1);

you can try

expect(onChange).toHaveBeenCalled();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.