reactjs - 输入 onChange 不更新玩笑和酶的状态
问题描述
import { BrowserRouter as Router } from "react-router-dom";
const setup = (props = {}, state = null,initialState={}) => {
const store = storeFactory(initialState);
const wrapper = mount(
<Router
<Component {...props} store={store}/>
</Router>
);
if (state) wrapper.setState(state);
return wrapper;
};
test("Rendered email input and test valid", () => {
const email = "";
const wrapper = setup(null, { email });
const emailInput = findByTestAttribute(
wrapper,
someId
);
emailInput.simulate("change", { target: { value: "email@email.com" } });
console.log(wrapper.state('email')) //Empty ""
expect(wrapper.state("email")).toBe("email@email.com");
});
wrapper.state('email') 应该返回 email@email.com 但它没有更新。有什么原因吗?
解决方案
您需要id
在模拟事件中传递:
emailInput.simulate("change", {
target: {
id: "your id here"
value: "email@email.com"
}
});
此外,由于更新是异步完成的,因此您应该在执行任何断言之前等待您的承诺。
定义一个flushPromises
函数:
function flushPromises() {
return new Promise(resolve => setImmediate(resolve));
}
然后在您的测试中等待承诺:
test("Rendered email input and test valid", () => {
const email = "";
const wrapper = setup(null, { email });
const emailInput = findByTestAttribute(
wrapper,
someId
);
emailInput.simulate("change", { target: { id: "your id here", value: "email@email.com" } });
await flushPromises; // await for promises to return
console.log(wrapper.state('email')) //Empty ""
expect(wrapper.state("email")).toBe("email@email.com");
});
推荐阅读
- android - 条码标签打印安卓
- php - 如果条件为真,Laravel 显示关系
- javascript - 在反应中将参数传递给事件处理程序
- php - 在 openssl_encrypt 中一次加密 2 个字符串
- filter - 如何根据价格条件自动收集按价格创建过滤器
- python - 是否有更高效的 pygame.key.get_pressed(pygame.K) 版本
- python - 使用 pyarrow 将结构列写入镶木地板
- swift - UITableCell 中的自定义卡片
- count - 将计数文本字段显示为零而不是空白
- angular - NativeScript 中的 Bluetooth-pulgin 存在问题:ERROR TypeError: ... is not a function?