NIsham Mahsin
NIsham Mahsin

Reputation: 728

React input onchange simulation not updating value using Jest and enzyme

I have a functional component as below

const Input = () => {
  const [value, updateValue] = useState("");
  return (
    <input
      type="text"
      id="input"
      value={value}
      onChange={(e) => {
        updateValue(e.target.value);
      }}
    />
  );
};

export default Input;

and test as below

const event = { target: { value: "Q" } };
input.simulate("change", event);
expect(input.prop("value")).toBe("Q");

the problem is that simulation of the event is not updating state. I tried wrapper.update() as well but it is not working.

you can run test here

Upvotes: 4

Views: 4755

Answers (2)

nambk
nambk

Reputation: 455

For those who got multiple inputs just like @NishamMahsin's case. I had the same issue and found the working solution from wrapper not updated after simulate('change'). #1999

In short:

.simulate('change', {target: {name: 'inputFirstName', value: 'value'}})

It took me quite a long time on this, so hope it helps someone here...

Upvotes: 1

skyboyer
skyboyer

Reputation: 23705

After component updated your input variable still points on old wrapper.

Wrappers(except root one) are immutable so you need to .find() element again.

So if you

const event = { target: { value: "Q" } };
input.simulate("change", event);
expect(wrapper.find("input").prop("value")).toBe("Q");

you will get it passed.

PS probably it's safer always avoid using intermediate variables while testing with Enzyme.

Upvotes: 8

Related Questions