在我的 react native 项目中,我最近安装了 node 模块 react-native-async-storage,因为我收到了有关“react-native”中的 native 包被弃用并移出到单个模块的警告。
安装后@react-native-community/async-storage
我的 Jest 测试失败了。
首先跟随error: unexpected token at position 0
在文件中:
持久性.js
import AsyncStorage from '@react-native-community/async-storage';
storeData = async ({ key, value }) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
// Error saving data
}
}
retrieveData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
if (value !== null) {
// Our data is fetched successfully
return value;
}
} catch (error) {
// Error retrieving data
}
}
module.exports = {
storeData,
retrieveData
}
所以我认为这与一些 babel 配置有关,因为我上次从 @react-native-community 安装包时遇到了类似的情况
所以,到
transformIgnorePatterns
在我的 package.json 中,我添加了以下内容: "jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!react-native|@react-native-community/async-storage|native-base-shoutem-theme|@shoutem/animation|@shoutem/ui|tcomb-form-native)"
]
}
但现在我遇到了一个新错误。
@RNCommunity/AsyncStorage: NativeModule.RCTAsyncStorage is null.
我正在粘贴屏幕截图以显示我的项目目录,以便您了解哪些配置文件可以处理。
正如我所看到的,大多数相关主题都是关于模拟我尝试这样做的 asyncStorage 函数,但没有任何运气。我在我唯一的测试文件中添加了以下内容:
import MockAsyncStorage from 'mock-async-storage';
beforeAll(() => {
const mockImpl = new MockAsyncStorage()
jest.mock('AsyncStorage', () => mockImpl)
snapshot = renderer.create(<App />);
})
afterAll(() => {
jest.unmock('AsyncStorage')
});
还是没有雪茄。我尝试添加
setupFilesAfterEnv.js
正如其他答案所暗示的那样,配置也没有奏效。
最佳答案
异步存储有 published instructions关于如何解决这个问题。
这是一个简短的版本:
export default from '@react-native-community/async-storage/jest/async-storage-mock'
我希望它可以帮助别人。
关于react-native - 安装 react-native-async-storage 后开 Jest 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418910/