React-testing-library: fireEvent.change not calling mock function

Created on 14 Jan 2019  路  3Comments  路  Source: testing-library/react-testing-library

  • react-testing-library version: 5.4.4
  • react version: 16.3.2
  • node version: 10.14.2
  • npm (or yarn) version: 1.13.0

Relevant code or config:

Here is my tree structure for the related element:

                        <div>
                          <label class="control-label"
                            for="id">Label</label>
                          <spanclass="input-group">
                            <span class="input-group-addon"/>
                            <input
                              class="form-control"
                              id="id"
                              placeholder="Enter"
                              type="number"
                              value=""
                            />
                            <span
                              class="actionItemDisabled cross input-group-addon"
                            />
                          </span>
                        </div>
import { render, fireEvent, cleanup, waitForElement, prettyDOM } from 'react-testing-library';
const props  = {
...,
handleChange: jest.fn(),
...
}

  it('User Inputs Number and changes dropdown but button is still disabled', () => {
    const tree = render(<Component {...props} />);
    const input = tree.getByLabelText(/(New Amount)/i);
    fireEvent.change(input);
    expect(props.handleChange.mock.calls.length).toBe(1);
  });

What you did:

yarn jest --watchAll

What happened:

Expected: 1
Received: 0

65 | expect(props.handleChange.mock.calls.length).toBe(1);

Problem description:

This should have called my mock function on change.

Suggested solution:

I haven't got one yet - but I will be working towards a solution.

Most helpful comment

Hi @chasen-bettinger!

For react to actually call your callback function, the change event has to change the value somehow, so try this:

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

All 3 comments

Hi @chasen-bettinger!

For react to actually call your callback function, the change event has to change the value somehow, so try this:

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

If you have further questions, please ask on the official support channel: https://spectrum.chat/react-testing-library

@kentcdodds

That works - thanks for the quick support. You're the man!

Was this page helpful?
0 / 5 - 0 ratings