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

如何解决Testing-Library/User-Event中Material-UI动画引发的act警告?

MUI Tab组件测试act警告的解决方案求助

我清楚不应该在用户事件外层包裹act(),因为Testing Library会自动处理这类逻辑,但不加的话测试就会抛出警告。以带涟漪效果的MUI Tab组件为例:

import { Tab as MuiTab } from "@mui/material";

describe("Tab", () => {

    it("MuiTab creates a warning ", async () => {
        const user = userEvent.setup();
        render(<MuiTab label="hello" />);

        // 此处会出现警告
        await user.click(screen.getByRole("tab"));
    });

    it("MuiTab does NOT create a warning with disableTouchRipple", async () => {
        const user = userEvent.setup();

        // 禁用动画可消除警告
        render(<MuiTab label="hello" disableTouchRipple />);

        await user.click(screen.getByRole("tab"));
    });

    it("MuiTab does NOT create a warning with act", async () => {
        const user = userEvent.setup();
        render(<MuiTab label="hello" />);

        // 无警告
        await act(async () => await user.click(screen.getByRole("tab")));
    });
});

这些警告是在我将@testing-library/react升级至^14.0.0版本后出现的(该版本修复了其他act相关警告),但现在整个测试套件里出现了170万行这类警告。我知道原因是测试结束时涟漪动画还未完成,也明白用Jest假定时器可以解决问题,但不想在整个测试套件中逐个添加act(),也不想大量使用假定时器。请问有没有更合适的推荐解决方案?

版本信息

  • "@mui/material": "^5.12.1"
  • "@testing-library/jest-dom": "^5.16.5"
  • "@testing-library/react": "^14.0.0"
  • "@testing-library/user-event": "^14.4.3"
  • "jest": "^29.5.0"

(注:无需提醒我点击后要添加断言逻辑,我清楚这一点,此处仅以Tab组件为例,无论是否添加expect语句都会出现该警告。)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:32:14