NIs*_*sin 3 javascript single-page-application reactjs jestjs enzyme
我有一个功能组件如下
const Input = () => {
const [value, updateValue] = useState("");
return (
<input
type="text"
id="input"
value={value}
onChange={(e) => {
updateValue(e.target.value);
}}
/>
);
};
export default Input;
Run Code Online (Sandbox Code Playgroud)
并测试如下
const event = { target: { value: "Q" } };
input.simulate("change", event);
expect(input.prop("value")).toBe("Q");
Run Code Online (Sandbox Code Playgroud)
问题是事件的模拟没有更新状态。我也试过 wrapper.update() 但它不起作用。
你可以在这里运行测试
组件更新后,您的input变量仍然指向旧包装器。
包装器(除根目录外)是不可变的,因此您需要.find()再次添加元素。
所以如果你
const event = { target: { value: "Q" } };
input.simulate("change", event);
expect(wrapper.find("input").prop("value")).toBe("Q");
Run Code Online (Sandbox Code Playgroud)
你会通过的。
PS可能更安全的是,在使用酶进行测试时始终避免使用中间变量。