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

Expo45升级至Expo48后单元测试报错:TypeError读取'exists'失败

解决Expo 48升级后单元测试中expo-asset的Cannot read properties of undefined (reading 'exists')错误

错误根源

该错误源于Jest测试环境中,expo-asset模块依赖的原生文件系统API未被正确模拟。Expo 48对expo-asset的内部实现做了调整,导致原Expo 45环境下的测试兼容逻辑失效,调用exists方法时出现undefined。

解决步骤

  • 确保expo-asset依赖匹配版本
    先确认项目中expo-asset已正确安装并适配Expo 48版本:

    npx expo install expo-asset
    
  • Mock expo-asset核心方法
    在项目根目录创建__mocks__/expo-asset.js文件,模拟expo-asset的关键方法:

    jest.mock('expo-asset', () => ({
      exists: jest.fn().mockResolvedValue(true),
      Asset: {
        fromModule: jest.fn(() => ({
          downloadAsync: jest.fn().mockResolvedValue({ localUri: 'mock-local-uri' }),
          uri: 'mock-uri',
        })),
      },
      // 根据组件实际用到的其他expo-asset方法补充mock
    }));
    

    也可在jest.config.js中配置全局mock。

  • 排查组件间接依赖
    检查UpdatePasswordScreen中用到的Spinner、CustomInput、Icon组件,它们可能内部使用expo-asset加载资源。若为第三方组件,需参考其文档补充对应mock逻辑。

  • 更新Jest预设配置
    确保jest.config.js使用Expo 48适配的Jest预设:

    module.exports = {
      preset: '@expo/jest-preset',
      testEnvironment: 'jsdom', // 若为Web测试使用,Native测试用node
      // 其他自定义配置
    };
    

    同步安装对应依赖:

    npm install --save-dev @expo/jest-preset jest
    
  • 适配异步渲染逻辑
    若组件内部存在异步资源加载操作,需用waitFor处理异步渲染:

    import { waitFor, screen } from '@testing-library/react-native';
    
    it('Should be able rendered properly', async () => {
      render(
        <UserContext.Provider value={[initialState, jest.fn()]}>
          <UpdatePasswordScreen />
        </UserContext.Provider>,
      );
      await waitFor(() => {
        expect(screen.getByText('Old password')).toBeInTheDocument();
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:15:02