React input onchange simulation not updating value using Jest and enzyme

自闭症网瘾萝莉.ら 提交于 2019-12-11 18:48:31

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/58129563/react-input-onchange-simulation-not-updating-value-using-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!