React-testing-library: Uncontrolled input value mutation

Created on 28 Nov 2018  路  9Comments  路  Source: testing-library/react-testing-library

Hi everyone,

How i can test uncontrolled input component?
I need to change the text of the input, and I tried to set directly the value of the dom node but the value is not changing and also to fire change event.
it looks like react does not know about the change of the input dom value.

Thanks.

Most helpful comment

Just change the way you fire the event to this:
fireEvent.change(input, { target: { value: "CHANGED VALUE" } });
and delete this line:
input.value = "CHANGED VALUE";

you can view example for this usage here:
https://github.com/kentcdodds/react-testing-library#fireeventeventnamenode-htmlelement-eventproperties-object

All 9 comments

Hi 馃憢

This is documented here: https://github.com/kentcdodds/react-testing-library/blob/master/README.md#fireeventnode-htmlelement-event-event

Good luck!

Hi Kent,

This document talk about controlled components and not uncontrolled input component.
when i trigger onChange event the value of the input is not changing, and also when i set the value property on the input dom node.

Thanks for the answer.

Hmmmmm... Could you reproduce the issue in this codesandbox? https://kcd.im/rcs

I am going to hijack this issue because I am trying to solve exactly the same thing.

Here is a simplified reproduction: https://codesandbox.io/s/3858vjrjpp

The onChange is never triggered in tests for some reason.

Just change the way you fire the event to this:
fireEvent.change(input, { target: { value: "CHANGED VALUE" } });
and delete this line:
input.value = "CHANGED VALUE";

you can view example for this usage here:
https://github.com/kentcdodds/react-testing-library#fireeventeventnamenode-htmlelement-eventproperties-object

@nadavkaner If you look closely, I am not using regular ev.target.value :) It's ref based approach mostly because of the TypeScript reasons.

The trigger event also change the value of the input, so this is also works..
This resemble the way your user will interact with this component in the real world

Wow, did not see that coming. You are completely right, it works. Thanks!

It could be probably mentioned in the docs that it will also modify the actual value of the input.

The above links to the docs no longer work - I think the same info is now at https://testing-library.com/docs/api-events#fireevent-eventname

Was this page helpful?
0 / 5 - 0 ratings