Skip to Content

Mocking AsyncStorage in React Native

10/06/2018

Being long overdue, I wanted to add tests to a simple AsyncStorage wrapper library of mine. After some struggle, I got a jest mock setup for AsyncStorage which I’m happy with. To save others the headache, the steps I followed where:

  • Install the following dependencies (assuming your starting from scratch):
yarn add --dev jest babel-jest babel-preset-react-native react-native
  • Add configuration to package.json for jest and babel. Remember to update the setupFiles path to where you keep yours:
  "jest": {
    "setupFiles": [
      "./jest/setup.js"
    ]
  },
  "babel": {
    "presets": [
      "react-native"
    ]
  }
jest.mock('react-native', () => {
    let items = {};

    return {
        AsyncStorage: {
            setItem: jest.fn((item, value) => {
                items[item] = value;
                return Promise.resolve(value);
            }),
            multiSet: jest.fn((item, value) => {
                item.forEach(([key, value]) => {
                    items[key] = value
                })
                return Promise.resolve(value);
            }),
            getItem: jest.fn((item, value) => {
                return Promise.resolve(items[item]);
            }),
            multiGet: jest.fn((keys) => {
                const result = keys.map(key => [key, items[key]])
                return Promise.resolve(result);
            }),
            removeItem: jest.fn((item) => {
                return Promise.resolve(delete items[item]);
            }),
            getAllKeys: jest.fn(() => {
                return Promise.resolve(Object.keys(items));
            }),
            clear: jest.fn((() => {
                items = {}
                return Promise.resolve()
            }))
        }
    }
});

After the configuration, your tests should be good to go.