我目前在为使用值的 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/