问题
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