react-native - 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 测试时,有人可以帮助我为什么会出现这个错误。我已经更新了几个开发依赖项,但没有运气。
解决方案
模拟 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;
});
推荐阅读
- java - 在 Dart 中解密 Java AES 编码的字符串
- python-pptx - Python 代码在我启动 Anaconda Navigator 但不在 env 中时运行
- c++ - 在 Visual Studio 2015 中为 R 编写 C++ 代码,链接器错误
- python - Python 为 Windows 生成 SOABI/扩展后缀 (pep 3149)
- amazon-web-services - 在 ECS 服务中存储 AWS 凭证的位置
- css - 如何为选定的文本设置突出显示颜色
- javascript - 联系表 7 - 与简码和价值相关
- gcc - 在 libxml2 for nix 中逐一包含目录
- azure - 是否可以使用 azure 应用程序洞察可用性测试将音频警报与电子邮件一起发送?
- c# - c# 将对象克隆到新变量