2

我在 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 测试时,有人可以帮助我为什么会出现这个错误。我已经更新了几个开发依赖项,但没有运气。

4

2 回答 2

1

模拟 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;
 });
于 2020-07-14T14:22:49.300 回答
0

解决方案是模拟包。

  1. 在您的项目根目录中,创建 __mocks__/@react-native-async-storage directory.
  2. 在该文件夹中,创建async-storage.js文件。
  3. 在该文件中,导出异步存储模拟。
export default from '@react-native-async-storage/async-storage/jest/async-storage-mock'

完整的说明在这里https://react-native-async-storage.github.io/async-storage/docs/advanced/jest

于 2021-04-15T15:12:26.780 回答