You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

userEvent.type在act包裹下仅输入最后一个字符,12.1.5版本仍未解决

Issue with user-event v12.1.5: Input only registers last character (despite fix in v12.0.1)

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 await to 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—manual act() 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 extra act() was triggering an edge case that wasn't covered by that fix.

内容的提问来源于stack exchange,提问作者medicengonzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:02:53