首页 > 解决方案 > 控制值时如何使用反应测试库将文本输入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=""
          />

标签: reactjsformikreact-testing-library

解决方案


你试过异步吗?如果该字段的值正确,则异步可能是问题所在。

 test("fills out profile name", async () => {
     const field = screen.getByLabelText("Profile Name");
     await userEvent.type(field, "profile name");
     expect(field).toHaveValue("profile name");
 });

推荐阅读