Skip to content Skip to sidebar Skip to footer

Sample Use Case To Test Async Storage With Jest-expo?

I have replicated an example to understand the testing of Mock-async-storage for reactjs. Any suggestions for a different approach of testing are welcome. I tried to replicate the

Solution 1:

Detailed Solution for the above:

Install the module using the command : Run this command from the root directory of the project.

npm install --save mock-async-storage

In the project root directory create __mocks__\@react-native-community folder. Inside that create a file async-storage.js. Code in async-storage.js

exportdefaultfrom'@react-native-community/async-storage/jest/async-storage-mock'

Inside package.json configure the jest as follows:

"jest": {
    "preset": "jest-expo",
    "transformIgnorePatterns" : ["/node_modules/@react-native-community/async-storage/(?!(lib))"]
  },

Here I am using jest-expo for testing. If you are using jest then the preset value will be jest not jest-expo.

In the project root directory create a file called jest.config.js Configuration inside the jest.config.js file:

module.exports = {
    setupFilesAfterEnv: [
      './setup-tests.js',
    ],
  };

In the project root directory create a file called setup-tests.js. Code in this file is :

importMockAsyncStoragefrom'mock-async-storage';

const mockImpl = newMockAsyncStorage();
jest.mock('@react-native-community/async-storage', () => mockImpl);

In the project root directory create the test file. Here I am calling it Example.test.js.

importAsyncStoragefrom'@react-native-community/async-storage';

beforeEach(() => {
    AsyncStorage.clear();
    // console.log(`After the data is being reset :`)// console.log(AsyncStorage)
});

it('can read asyncstorage', async () => {

    awaitAsyncStorage.setItem('username', 'testUser')
    let usernameValue = awaitAsyncStorage.getItem('username')
    // console.log(`After the data is being set :`)// console.log(AsyncStorage)expect(usernameValue).toBe('testUser')
});

Here setting the value of username to testUser using AsyncStorage.setItem. Then fetching the value using getItem function. The test case is to compare whether the usernameValue is equal to testUser. If yes then the test case passes else the test case will fail.

Using beforeEach so that every time a test case is being run Asyncstorage is being cleared and is empty. If needed one can check what is present in Asyncstorage using console.log

Run the command yarn test to run the tests. The output is:

enter image description here

Post a Comment for "Sample Use Case To Test Async Storage With Jest-expo?"