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 the translation between DB and AsyncStorage though. Therefore, I want to make sure that AsyncStorage has the data I believe it does by running automated tests against it. Surprisingly, I haven't found any information on how to do that online. My attempts to do it on my own haven't worked out.
Using Jest:
it("can read asyncstorage", () => { return AsyncStorage.getItem('foo').then(foo => { expect(foo).not.toBe(""); }); });
This method failed with an error:
TypeError: RCTAsyncStorage.multiGet is not a function
Removing the return will cause it to run instantly without waiting for the value and improperly pass the test.
I got hit with the exact same error when I tried to test it using the await keyword:
it('can read asyncstorage', async () => { this.foo = ""; await AsyncStorage.getItem('foo').then(foo => { this.foo = foo; }); expect(foo).not.toBe(""); });
Any suggestions on how to successfully run assertions against the values in AsyncStorage? I'd prefer to continue using Jest but if it can only be done with some alternate testing library I'm open to that.
Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.
AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system.
Async Storage is great but it lacks security. This is less than ideal when storing sensitive data such as access tokens, payment information and so on. This module aims to solve this problem by providing a wrapper around Android's EncryptedSharedPreferences and iOS' Keychain , complete with support for TypeScript.
For everyone who sees this question in > 2019:
Since Nov 2020, AsyncStorage was renamed back to @react-native-async-storage/async-storage", which causes this warning to appear if you're importing it from react-native
:
Warning: Async Storage has been extracted from react-native core and will be removed in a future release.
The new module includes its own mock, so you don't have to worry about writing your own anymore.
Per the project's documentation, you can set it up in 2 different ways:
##With mocks directory
__mocks__/@react-native-community
directory.export default from '@react-native-async-storage/async-storage/jest/async-storage-mock'
Jest should then mock AsyncStorage
by default in all your tests. If it doesn't, try calling jest.mock(@react-native-async-storage/async-storage)
at the top of your test file.
package.json
or jest.config.js
) add the setup file's location: "jest": { "setupFiles": ["./path/to/jestSetupFile.js"] }
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'; jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);
If you're using TypeScript, using the 2nd option (Jest setup file) is way easier, since with the 1st one (mocks directory) it won't associate @types/react-native-community__async-storage
with the mock automatically.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With