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

@testing-library/react-native渲染简单导航组件触发jest超时问题

解决方案

按照以下优先级依次排查修改即可解决超时问题:

1. 修正导航容器嵌套问题

检查你的测试代码是否重复嵌套了NavigationContainer:你提供的组件默认导出已经内置了NavigationContainer,如果测试时渲染的是这个默认导出组件,不需要在外层额外加NavigationContainer,重复嵌套会导致导航逻辑异常卡住。如果测试的是单独导出的AppStack1组件,才需要在外层套NavigationContainer。

2. 禁用导航动画(测试环境专属)

React Navigation默认的进场/退场动画是异步执行的,在Jest测试环境下会导致渲染等待超时,需要手动关闭:

  • 测试时给NavigationContainer加上禁用动画的配置:
const { findByText } = render(
  <NavigationContainer theme={{ animation: 'none' }}>
    <AppStack1 />
  </NavigationContainer>
);
  • 给栈导航全局关闭动画:
// 修改AppStack1的Stack.Navigator配置
<Stack.Navigator screenOptions={{ animationEnabled: false }}>
  <Stack.Screen name='Screen1' component={Screen1} />
  <Stack.Screen name='Screen2' component={Screen2} />
</Stack.Navigator>

3. 修正测试用例的异步查询逻辑

你当前使用的getByText是同步查询,导航栈的渲染是异步过程,同步查询会因为元素还未挂载导致测试卡住,换成异步的findBy*查询即可,findBy*是同步查询和waitFor的组合,会自动等待元素渲染完成:

// 修改后的测试用例
it('renders the correct screen', async () => {
  const { findByText } = render(
    <NavigationContainer theme={{ animation: 'none' }}>
      <AppStack1 />
    </NavigationContainer>
  );
  // 最长等待10秒,匹配元素后继续执行
  const screenText = await findByText('Screen 1', { timeout: 10000 });
  expect(screenText).toBeDefined();
}, 15000); // 给当前用例单独设置15秒超时,覆盖默认5秒限制

4. 完善Jest转译配置

你当前的transformIgnorePatterns配置只处理了react-native相关包,@react-navigation系列包是ES模块,默认不会被转译,会导致运行异常卡住,修改Jest配置对应字段:

"transformIgnorePatterns": [
  "node_modules/(?!(@react-native|react-native|@react-navigation))"
]

5. 全局调整超时时间(可选)

如果所有测试用例都存在超时问题,可以在测试文件顶部或者Jest全局setup文件中添加配置,延长默认超时时间:

jest.setTimeout(15000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:54:03