Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fireEvent not properly calling event in react-testing-library

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.

like image 636
Zach Avatar asked Sep 11 '18 16:09

Zach


People also ask

What is react-testing-library?

Here is where we find react-testing-library (or @testing-library/react, as its package name). This library will help us to approach our testing from a user experience perspective, as it will give us tools not to test the implementation details of the component, but to test the user behaviour.

Why use fireevent instead of userevent to trigger onfocus?

For example, if we want to test if our input doesn't execute the onChange method if it has not been focused, using userEvent will trigger the onFocus event, which will make it impossible for us to test that behaviour. In this case, fireEvent would be the chosen one so we can trigger only and specifically that event.

Why do we need fireevent tool?

If we want to interact with our components and elements in our tests we should be capable to simulate those interactions, and that's the reason why this library includes the fireEvent tool, which will allow us to trigger events in our DOM elements and simulate the events that the user would trigger in their interactions.

Why is testing important in react development?

When we develop our React applications there is a part which is as important as the development itself, and which sometimes is left behind: the testing. With an appropriate testing we can adjust and change our code knowing that our application (or our components) will continue working as expected since, otherwise, our tests will warn us about it.


1 Answers

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.

like image 91
Zach Avatar answered Nov 15 '22 08:11

Zach