fireEvent not properly calling event in react-testing-library
Asked Answered
C

2

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.

Clydesdale answered 11/9, 2018 at 16:49 Comment(1)
This has been noted as an issue in Github [CLOSED].Hartung
C
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.

Clydesdale answered 19/9, 2018 at 18:40 Comment(0)
Q
1

Instead of calling this

expect(onChange).toHaveBeenCalledTimes(1);

you can try

expect(onChange).toHaveBeenCalled();
Quartana answered 27/11, 2021 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.