Test Driven Development with AsyncStorage

Author

Spencer Carli

Developer, cat dad, and devout pizza lover. Teaching at React Native School and building apps with Handlebar Labs.

Last Updated: July 31, 2019

setup-tests.js

import MockAsyncStorage from 'mock-async-storage';

const mockImpl = new MockAsyncStorage();
jest.mock('@react-native-community/async-storage', () => mockImpl);

recentSearch.js

import AsyncStorage from '@react-native-community/async-storage';

export const saveRecentSearch = async (recentSearch) => {
  try {
    const existingSearch = await getRecentSearch();
    const newRecentSearch = [recentSearch, ...existingSearch];
    return AsyncStorage.setItem(
      'DEMO::recentSearch',
      JSON.stringify(newRecentSearch)
    );
  } catch (err) {
    return;
  }
};

export const getRecentSearch = async () => {
  try {
    const result = await AsyncStorage.getItem('DEMO::recentSearch');
    if (result) {
      return JSON.parse(result);
    }

    return [];
  } catch (err) {
    return [];
  }
};

__tests__/recentSearch.test.js

import { getRecentSearch, saveRecentSearch } from '../recentSearch';
import AsyncStorage from '@react-native-community/async-storage';

beforeEach(async () => {
  await AsyncStorage.clear();
});

describe('getRecentSearch', () => {
  test('if no results exist at key, return an empty array', async () => {
    const result = await getRecentSearch();
    expect(result).toEqual([]);
  });

  test('returns an array of recent searches', async () => {
    await AsyncStorage.setItem(
      'DEMO::recentSearch',
      JSON.stringify([{ id: 1 }])
    );
    const result = await getRecentSearch();
    expect(result).toEqual([{ id: 1 }]);
  });
});

describe('saveRecentSearch', () => {
  test('if no recent search exists, adds item', async () => {
    await saveRecentSearch({ id: 1 });

    const result = await getRecentSearch();
    expect(result).toEqual([{ id: 1 }]);
  });

  test('adds the latest search to the start of the array', async () => {
    await saveRecentSearch({ id: 1 });
    await saveRecentSearch({ id: 2 });

    const result = await getRecentSearch();
    expect(result).toEqual([{ id: 2 }, { id: 1 }]);
  });

  // limits the result of recent search to 3
  // accept optional second argument to clear all recent searches
});
React Native School Logo

React Native School

Want to further level up as a React Native developer? Join React Native School! You'll get access to all of our classes and our private Slack community.