jest test fails after installing react-native-async-storage
async-storage has published instructions on how to solve this issue.
Here is a shorten version:
- In your project root directory, create __mocks__/@react-native-community directory.
- Inside that folder, create a async-storage.js file.
- Copy paste the following inside that file:
export default from '@react-native-community/async-storage/jest/async-storage-mock'
- Enjoy!
I hope it can help others.
I found a way of mocking the @react-native-community/async-storage
in root of my project, (same dir as __test__
dir), I created a dir structure like this:
__mocks__/@react-native-community/async-storage/index.js
in index.js I mocked the following functions:
let cache = {};
export default {
setItem: (key, value) => {
return new Promise((resolve, reject) => {
return (typeof key !== 'string' || typeof value !== 'string')
? reject(new Error('key and value must be string'))
: resolve(cache[key] = value);
});
},
getItem: (key, value) => {
return new Promise((resolve) => {
return cache.hasOwnProperty(key)
? resolve(cache[key])
: resolve(null);
});
},
removeItem: (key) => {
return new Promise((resolve, reject) => {
return cache.hasOwnProperty(key)
? resolve(delete cache[key])
: reject('No such key!');
});
},
clear: (key) => {
return new Promise((resolve, reject) => resolve(cache = {}));
},
getAllKeys: (key) => {
return new Promise((resolve, reject) => resolve(Object.keys(cache)));
},
}
in my test file i added this:
beforeAll(() => {
jest.mock('@react-native-community/async-storage');
})
Screenshot of dir structure:
This did the trick. I found inspiration here: https://github.com/react-native-community/react-native-async-storage/issues/39