reactjs - 当值受控制时,如何使用React测试库将文本输入formik?

标签 reactjs formik react-testing-library

我目前在为使用值的 formik 字段编写测试时遇到问题。如果我使用defaultValue而不是值,我已经设法让我的测试正常工作,但我需要使用值。我尝试在 onChange 中使用 console.log 并知道文本正在流过它,但我不明白为什么它没有设置。我需要更改什么才能使其正常工作?

我尝试测试的代码示例

    <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");
 });

关于reactjs - 当值受控制时,如何使用React测试库将文本输入formik?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65260799/

相关文章:

javascript - 如何在 react 前端显示 Google Passport oAuth 同意屏幕,而不是使用快速 View 模板

javascript - 如何使用 React 从 ReqRes API 渲染用户列表

reactjs - 使用 Formik/Yup 进行可选文件验证

javascript - 如何正确使用 Formik 的 setError 方法? ( react 库)

react-native - 测试 Pressable 的按下状态

reactjs - 测试在 fireEvent.click in react-testing-library 之后是否仅在 radiogroup 组件中选择了 1 个单选按钮

ReactJs ErrorBoundary 在最简单的情况下不起作用

javascript - react 无状态组件不工作

javascript - 在 React 中根据状态设置表单的值

javascript - 模拟服务工作人员-预期响应解析器返回模拟响应对象,但未定义。将使用原始响应