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:

  1. In your project root directory, create __mocks__/@react-native-community directory.
  2. Inside that folder, create a async-storage.js file.
  3. Copy paste the following inside that file:
export default from '@react-native-community/async-storage/jest/async-storage-mock'
  1. 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: enter image description here

This did the trick. I found inspiration here: https://github.com/react-native-community/react-native-async-storage/issues/39