dom-testing-library version: 2.9.1react version:node version:npm (or yarn) version: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();
});
writing a test for an input.
component was using event.currentTarget.value, but got an error in the test because currentTarget was not defined.
change the code above to use current target instead.
@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.
Most helpful comment
found a solution:
https://stackoverflow.com/questions/40676343/typescript-input-onchange-event-target-value
closing.