userEvent.type在act包裹下仅输入最后一个字符,12.1.5版本仍未解决
Hey there, I see you're running into a frustrating issue where a bug marked as fixed in user-event v12.0.1 is still popping up in v12.1.5. Let's break down what's going on and how to fix it.
Your Test Code
import React, { Fragment } from "react"; import { render, act } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import App from "./App"; test("Gets a code and renders it in a new route", () => { const { getByLabelText } = render(<App />); act(() => { userEvent.type(getByLabelText("Code:"), "12345"); }); expect(getByLabelText("Code:")).toHaveValue("12345"); });
Error You're Seeing
● Gets a code and renders it in a new route
expect(element).toHaveValue(12345)
Expected the element to have value: 12345
Received: 5
What's Causing This?
The problem boils down to unnecessary use of act() with user-event v12+.
Starting in v12, user-event handles all the asynchronous event processing and wraps its actions in act() automatically. When you manually wrap userEvent.type() in another act() call, you're messing with the sequential firing of input events. This causes only the final character ("5") to be properly processed and updated in the component state, while the rest get lost in the mix.
The Fix
Remove the manual act() wrapper, and remember to await the userEvent.type() call (since it's asynchronous now):
import React, { Fragment } from "react"; import { render } from "@testing-library/react"; // No need to import act anymore import userEvent from "@testing-library/user-event"; import App from "./App"; test("Gets a code and renders it in a new route", async () => { const { getByLabelText } = render(<App />); await userEvent.type(getByLabelText("Code:"), "12345"); expect(getByLabelText("Code:")).toHaveValue("12345"); });
Quick Notes to Remember:
- user-event v12+ methods are async, so always use
awaitto make sure all events finish before you run your assertions. - React Testing Library and modern user-event versions handle
act()under the hood for you—manualact()calls are almost never needed anymore, and can cause weird edge cases like this one. - The fix in v12.0.1 was meant for the correct usage pattern (without manual
act()). Your extraact()was triggering an edge case that wasn't covered by that fix.
内容的提问来源于stack exchange,提问作者medicengonzo

