Async Storage module is tighly coupled with its NativeModule
part - it needs a running React Native application to work properly. In order to use it in tests, you have to provide its separate implementation. Follow those steps to add a mocked Async Storage
module.
You can use one of two ways to provide mocked version of AsyncStorage
:
- In your project root directory, create
__mocks__/@react-native-community
directory. - Inside that folder, create
async-storage.js
file. - Inside that file, export
Async Storage
mock.
export default from '@react-native-community/async-storage/jest/async-storage-mock'
- In your Jest config (probably in
package.json
) add setup files location:
"jest": {
"setupFiles": ["./path/to/jestSetupFile.js"]
}
- Inside your setup file, set up Async Storage mocking:
import mockAsyncStorage from '@react-native-community/async-storage/jest/async-storage-mock';
jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);
Each public method available from Async Storage
is a mock function, that you can test for certain condition, for example, if .getItem
has been called with a specific arguments:
it('checks if Async Storage is used', async () => {
await asyncOperationOnAsyncStorage();
expect(AsyncStorage.getItem).toBeCalledWith('myKey');
})
You can override mock implementation, by replacing its inner functions:
// somewhere in your configuration files
import AsyncStorageMock from '@react-native-community/async-storage/jest/async-storage-mock';
AsyncStorageMock.multiGet = jest.fn(([keys], callback) => {
// do something here to retrieve data
callback([]);
})
export default AsyncStorageMock;
You can check its implementation to get more insight into methods signatures.
Note: In React Native 0.60+, all @react-native-community
packages are transformed by default.
You need to point Jest to transform this package. You can do so, by adding Async Storage path to transformIgnorePatterns
setting in Jest's configuration.
"jest": {
"transformIgnorePatterns": ["node_modules/(?!(@react-native-community/async-storage/lib))"]
}
Optionally, you can transform whole scope for react-native-community
and react-native
:
"jest": {
"transformIgnorePatterns": ["node_modules/(?!(@react-native-community|react-native))"]
}