How to test Async Storage with Jest?

前端 未结 6 839
悲哀的现实
悲哀的现实 2020-12-05 18:02

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 t

6条回答
  •  广开言路
    2020-12-05 18:27

    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

    export default from '@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 :

    import MockAsyncStorage from 'mock-async-storage';
    
    const mockImpl = new MockAsyncStorage();
    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.

    import  AsyncStorage  from '@react-native-community/async-storage';
    
    beforeEach(() => {
        AsyncStorage.clear();
        // console.log(`After the data is being reset :`)
        // console.log(AsyncStorage)
    });
    
    it('can read asyncstorage', async () => {
    
        await AsyncStorage.setItem('username', 'testUser')
        let usernameValue = await AsyncStorage.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:

提交回复
热议问题