How to test Async Storage with Jest?

前端 未结 6 836
悲哀的现实
悲哀的现实 2020-12-05 18:02

I\'m building an app with React Native. I want to minimize how often I communicate to the database, so I make heavy use of AsyncStorage. There\'s a lot of room for bugs in t

6条回答
  •  孤城傲影
    2020-12-05 18:34

    May be you can try something like this:

    mockStorage.js

    export default class MockStorage {
      constructor(cache = {}) {
        this.storageCache = cache;
      }
    
      setItem = jest.fn((key, value) => {
        return new Promise((resolve, reject) => {
          return (typeof key !== 'string' || typeof value !== 'string')
            ? reject(new Error('key and value must be string'))
            : resolve(this.storageCache[key] = value);
        });
      });
    
      getItem = jest.fn((key) => {
        return new Promise((resolve) => {
          return this.storageCache.hasOwnProperty(key)
            ? resolve(this.storageCache[key])
            : resolve(null);
        });
      });
    
      removeItem = jest.fn((key) => {
        return new Promise((resolve, reject) => {
          return this.storageCache.hasOwnProperty(key)
            ? resolve(delete this.storageCache[key])
            : reject('No such key!');
        });
      });
    
      clear = jest.fn((key) => {
        return new Promise((resolve, reject) =>  resolve(this.storageCache = {}));
      });
    
      getAllKeys = jest.fn((key) => {
        return new Promise((resolve, reject) => resolve(Object.keys(this.storageCache)));
      });
    }
    

    and inside your test file:

    import MockStorage from './MockStorage';
    
    const storageCache = {};
    const AsyncStorage = new MockStorage(storageCache);
    
    jest.setMock('AsyncStorage', AsyncStorage)
    
    // ... do things
    

提交回复
热议问题