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

React Native TypeScript Jest测试报AsyncStorage is null如何解决?

报错解决方案

核心问题根源

你当前mock的AsyncStorage包名和代码中实际导入的包名不匹配,mock规则未生效,导致jest加载了原生版本的AsyncStorage触发报错。

具体修复步骤

    1. 统一包名导入规范
      当前@react-native-community/async-storage已废弃,所有业务代码、测试代码中的导入语句统一替换为新版本包名:
    // 替换前(错误)
    import AsyncStorage from "@react-native-community/async-storage"
    // 替换后(正确)
    import AsyncStorage from "@react-native-async-storage/async-storage"
    
    1. 校验jest配置加载规则
      在package.json的jest配置段或jest.config.js中,确认已经添加setup文件加载配置,确保mock逻辑会在测试运行前执行:
    {
      "jest": {
        "preset": "react-native",
        "setupFiles": ["<rootDir>/test/setup.ts"]
      }
    }
    
    1. 修正测试用例语法
      @testing-library/react-native的render方法为同步方法,不需要加await;若AsyncStorage的调用为组件内异步触发,断言需要用waitFor包裹:
    import AsyncStorage from "@react-native-async-storage/async-storage"
    import { render, waitFor } from "@testing-library/react-native"
    import React from "react"
    import { LoginScreen } from ".."
    
    it("renders correctly", async () => {
      const { getAllByText } = render(<LoginScreen navigation={undefined} route={undefined} />)
      expect(getAllByText("Login").length).toBe(1)
      await waitFor(() => {
        expect(AsyncStorage.getItem).toBeCalledWith("myKey")
      })
    })
    
    1. 兜底兼容方案
      若存在旧代码无法统一替换包名的情况,可直接在jest配置中添加包名映射规则,无需单独编写mock文件:
    {
      "jest": {
        "moduleNameMapper": {
          "^@react-native-community/async-storage$": "@react-native-async-storage/async-storage/jest/async-storage-mock",
          "^@react-native-async-storage/async-storage$": "@react-native-async-storage/async-storage/jest/async-storage-mock"
        }
      }
    }
    

完成以上修改后清空jest缓存,重新运行测试即可:npx jest --clearCache


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:54:00