Dom-testing-library: event.currentTarget not populated when fireevent.change happens for an input.

Created on 16 Jul 2018  Â·  4Comments  Â·  Source: testing-library/dom-testing-library

  • dom-testing-library version: 2.9.1
  • react version:
  • node version:
  • npm (or yarn) version:

Relevant code or config:

import React, { Component } from 'react';

export class Input extends Component {

  constructor(props) {
    super();

    const {
      value
    } = props;

    this.state = {
      value: value || ''
    };
  }

  handleChange = (evt) => {
    const {
      onChange
    } = this.props;

    this.setState(prevState => ({
      value: evt.target.value
    }));

    if (onChange) {
      onChange( evt.target.value);
    }

  }

  render() {
    const {
      value
    } = this.state;

    return (
      <input onChange={this.handleChange} value={value} data-testid="input" />
    )
  }
}



// test

test('will call onChange prop if changes occur', async () => {
    const spy = jest.fn();
  const {getByText, getByTestId, container} = render(<Input value="test" onChange={spy} />);

  expect(getByTestId('input')).toHaveAttribute('value', 'test');

  const input = getByTestId('input');

  input.value = 'testing';

  fireEvent.change(
    input
  );

    expect(getByTestId('input')).toHaveAttribute('value', 'testing');
    expect(spy).toHaveBeenCalled();
  // expect(container.firstChild).toMatchSnapshot();
});

What you did:

writing a test for an input.

What happened:

component was using event.currentTarget.value, but got an error in the test because currentTarget was not defined.

Reproduction:

change the code above to use current target instead.

Problem description:

Suggested solution:

Most helpful comment

found a solution:
https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value

evt: React.ChangeEvent<HTMLInputElement>

closing.

All 4 comments

@kentcdodds any thoughts on this?

Hi @kelly-tock!

So currentTarget represents the target upon which the event handler was added. React adds event handlers to document.body. If it works for you to use currentTarget in your application code it's probably because react is doing something special with the events and somehow that's not applying in this case I guess.

In any case, I think it's generally better to use target. Please let me know if I'm misunderstanding something.

Yes my main concern is that if you are using flow or typescript the event definition doesn’t let you use target to get the value off of. ‘React.SyntheticEvent’

If there’s a different way to define the event in either of those than that should work.

found a solution:
https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value

evt: React.ChangeEvent<HTMLInputElement>

closing.

Was this page helpful?
0 / 5 - 0 ratings