Skip to content

Instantly share code, notes, and snippets.

@oshimayoan
Created May 3, 2019 08:24
Show Gist options
  • Save oshimayoan/5e842e79e0de44be0b9ce262f98777ba to your computer and use it in GitHub Desktop.
Save oshimayoan/5e842e79e0de44be0b9ce262f98777ba to your computer and use it in GitHub Desktop.
Mocking AsyncStorage
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!'); //eslint-disable-line
});
});
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)));
});
}
// Your imported dependencies goes here
import MockStorage from '../path/to/__mocks__/mockStorage';
let storageCache = {};
const AsyncStorage = new MockStorage(storageCache);
jest.setMock('AsyncStorage', AsyncStorage);
describe('Something to test', () => {
// Your test goes here
})
@AudyOdi
Copy link

AudyOdi commented May 3, 2019

cannot :(

 SecureStore [ 'deleteItemAsync',
      'getItemAsync',
      'setItemAsync',
      'AFTER_FIRST_UNLOCK',
      'AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY',

I didn't put any AFTER_FIRST_UNLOCK mock thing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment