首页 > 解决方案 > TypeError:无法读取未定义的属性“PlatformLocalStorage”

问题描述

我在 react-native 上运行 jest test 并得到以下错误

测试套件无法运行

TypeError: Cannot read property 'PlatformLocalStorage' of undefined

  2 | import thunk from 'redux-thunk';
  3 | import { persistStore, persistReducer } from 'redux-persist';
> 4 | import AsyncStorage from '@react-native-community/async-storage';
    | ^
  5 | 
"dependencies":{
    "react": "16.8.3",
    "react-native": "0.59.9",
},
"devDependencies": {
  "jest": "^24.1.0",
  "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.10.0",
},

  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/__tests__/setup/test-setup.js"
    ],
    "setupFiles": [
      "<rootDir>/__tests__/setup/test-setup.js"
    ],
    "transformIgnorePatterns": [
      "/node_modules(?![\\/]rn-fetch-blob[\\/]|[\\/]react-native[\\/]|[\\/]react-native-config[\\/]|[\\/]react-native-navigation[\\/]|[\\/]react-native-status-bar-height[\\/]|[\\/]react-native-animatable[\\/]|[\\/]react-native-restart[\\/]|[\\/]react-native-linear-gradient[\\/]|[\\/]react-native-i18n[\\/]|[\\/]react-native-modal[\\/]|[\\/]react-native-smooth-pincode-input[\\/]|[\\/]react-native-swipe-gestures[\\/]|[\\/]react-native-root-toast[\\/]|[\\/]react-native-root-siblings[\\/]|[\\/]static-container[\\/]|[\\/]react-native-elements[\\/]|[\\/]react-native-ratings[\\/]|[\\/]react-native-progress[\\/]|[\\/]react-native-dialog[\\/]|[\\/]react-native-pdf[\\/]|[\\/]react-native-webview[\\/]|[\\/]react-native-check-box[\\/]|[\\/]react-native-share[\\/]|[\\/]react-native-haptic-feedback[\\/]|[\\/]react-native-responsive-screen[\\/]|[\\/]react-native-keyboard-aware-scroll-view[\\/]|[\\/]he[\\/]|[\\/]react-native-iphone-x-helper[\\/]|[\\/]check-prop-types[\\/]|[\\/]react-native-image-progress[\\/]|[\\/]react-native-theming[\\/]|[\\/]@react-native-community/async-storage[\\/])/"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/(build|docs|node_modules)/",
      "<rootDir>/__tests__/setup"
    ],
    "preset": "react-native"
  },
  "rnpm": {
    "assets": [
      "fonts"
    ]
  }
}

当我在 react-native 应用程序中运行 jest 测试时,有人可以帮助我为什么会出现这个错误。我已经更新了几个开发依赖项,但没有运气。

标签: react-nativejestjsenzymeenzyme-to-snapshot

解决方案


模拟 AsyncStorage 库。如果像我一样,您已经从react-native变体移植到react-native-community可能需要更新模拟的那个(如果您已经拥有它们)。

jest.mock("@react-native-community/async-storage", () => {
   // a map/dict/kvs of types to return - the leaves of the def
   // are jest functions
   const apiMock = {
    getItem: jest.fn(() => {  // mock's AsyncStorage.getItem()
      return JSON.stringify("some mock data");
    }),
   };
   return apiMock;
 });

推荐阅读