mock-async-storage
v2.9.0
Published
Its a mock of react-native AsyncStorage for jest tests
Downloads
51,851
Maintainers
Readme
Its a mock of react-native AsyncStorage for jest tests
From 2.9.x version, added esmodules support.
I suggest to use this library with setupFilesAfterEnv configuration. Its more stable and during my tests its working as expected.
NPM
// jest.config.js
module.exports = {
setupFilesAfterEnv: [
'<rootDir>/setup-tests.js',
],
};
// setup-tests.js
import MockAsyncStorage from 'mock-async-storage';
const mockImpl = new MockAsyncStorage();
jest.mock('@react-native-community/async-storage', () => mockImpl);
import MockAsyncStorage from "mock-async-storage";
jest.mock(
"@react-native-async-storage/async-storage",
() => new MockAsyncStorage()
);
import MockAsyncStorage from 'mock-async-storage';
// or import { mock, release } from 'mock-async-storage';
// mock();
// release();
const mock = () => {
const mockImpl = new MockAsyncStorage()
jest.mock('AsyncStorage', () => mockImpl)
}
const release = () => jest.unmock('AsyncStorage')
mock();
// For unmock
mockStorage.release();
Working example:
import 'react-native';
import MockAsyncStorage from 'mock-async-storage'
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
const mock = () => {
const mockImpl = new MockAsyncStorage()
jest.mock('AsyncStorage', () => mockImpl)
}
mock();
import { AsyncStorage as storage } from 'react-native'
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
it('Mock Async Storage working', async () => {
await storage.setItem('myKey', 'myValue')
const value = await storage.getItem('myKey')
expect(value).toBe('myValue')
})
In your test codes:
const mockStorage = require('mock-async-storage');
// or import { mock, release } from 'mock-async-storage';
// mock();
// release();
// For mock AsyncStorage
mockStorage.mock();
// For unmock
mockStorage.release();
Working example:
import 'react-native';
import { mock, release } from 'mock-async-storage'
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
mock()
import { AsyncStorage as storage } from 'react-native'
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
it('Mock Async Storage working', async () => {
await storage.setItem('myKey', 'myValue')
const value = await storage.getItem('myKey')
expect(value).toBe('myValue')
})