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

测试MUI Drawer组件时,如何修复‘Transition未包裹在act(...)中’警告?

解决MUI Drawer过渡引发的act警告问题

方法1:等待异步过渡完成

MUI Drawer的过渡逻辑即使设置transitionDuration={0},内部仍可能残留异步处理。可以在act后显式等待异步操作结束:

await act(async () => {
  component.setProps({ location: { hash: '#audit-trail' } });
  // 等待微任务队列清空,确保过渡相关异步逻辑执行完毕
  await new Promise(resolve => setTimeout(resolve, 0));
});

如果使用React Testing Library,也可以用waitFor配合断言等待状态稳定:

await act(() => {
  component.setProps({ location: { hash: '#audit-trail' } });
});

await waitFor(() => {
  // 这里添加针对Drawer状态的断言,比如检查Drawer是否可见
});

方法2:测试时禁用过渡组件

直接给Drawer传入无过渡的自定义组件,跳过过渡逻辑:

  1. 测试渲染组件时传入自定义过渡组件:
render(
  <YourComponent 
    location={{ hash: '#audit-trail' }}
    drawerTransition={({ children }) => <div>{children}</div>}
  />
);
  1. 在Drawer组件中接收并使用该props:
<Drawer
  anchor='right'
  open={this.props.location.hash.startsWith(`#audit-trail`)}
  TransitionComponent={this.props.drawerTransition}
/>

方法3:改用React Testing Library的自动act处理

如果还在使用Enzyme,可考虑切换到React Testing Library,它会自动将所有异步操作包裹在act中:

render(<YourComponent />);
// 模拟hash变化并触发事件
window.location.hash = '#audit-trail';
fireEvent(window, new Event('hashchange'));

// 等待断言
await waitFor(() => {
  expect(screen.getByRole('dialog')).toBeInTheDocument();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:50:38