reactjs - 控制值时如何使用反应测试库将文本输入formik?
问题描述
我目前在为使用值的 formik 字段编写测试时遇到问题。如果我使用 defaultValue 而不是 value 但我需要使用 value,我已经设法让我的测试工作。我试图 console.log 登录 onChange 并知道文本正在流经它,但我不明白为什么它没有设置。我需要更改什么才能使其正常工作?
我正在尝试测试的代码示例
<TextField
id="name"
label="Profile Name"
onChange={formik.handleChange}
value={formik.values.name}
required
</TextField>
测试工作的代码示例
<TextField
id="name"
label="Profile Name"
onChange={formik.handleChange}
defaultValue={formik.values.name}
required
</TextField>
当前失败的测试
test("fills out profile name", () => {
const field = screen.getByLabelText("Profile Name");
userEvent.type(field, "profile name");
expect(field).toHaveValue("profile name");
});
告诉我文本的 screen.debug 没有被设置。
<input
aria-invalid="false"
aria-labelledby="TextFieldLabel24"
class="ms-TextField-field field-80"
id="name"
required=""
type="text"
value=""
/>
解决方案
你试过异步吗?如果该字段的值正确,则异步可能是问题所在。
test("fills out profile name", async () => {
const field = screen.getByLabelText("Profile Name");
await userEvent.type(field, "profile name");
expect(field).toHaveValue("profile name");
});
推荐阅读
- swift - 尽管使用了完成块,但仍无法处理与数据检索相关的 Firebase 异步 API 调用问题
- ruby - 测试一个抽象的 if 条件
- python - 如何让烧瓶使用 docker 主机安装正确重新加载?
- ssrs-2012 - SSRS 将文本框绑定到查询中的字段
- mongodb - 如何在 mongodb 中将 NumberDecimal 值相乘
- java - 如何使用 mapreduce 作业聚合和显示前 n 个项目
- css - 在侧边栏中使用自定义样式
- react-native - 无法从 Axios 中获取数据
- javascript - 未捕获的 SyntaxError:计算时出现意外标识符
- jpype - python.exe中发生未处理的win32异常