Search code examples
react-nativejestjsasyncstorage

Mocking react-native-async-storage on Jest


I am testing functions which depend on @react-native-community/async-storage, so obviously my tests must mock that library.

And so I do this inside of my jestSetupFile.js:

import mockAsyncStorage from '@react-native-community/async-storage/jest/async-storage-mock';
jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);

Which is direct instruction from https://github.com/react-native-community/react-native-async-storage/blob/master/docs/Jest-integration.md

However, the file being exported has type keywords, which my JavaScript environment cannot parse:

  ● Test suite failed to run

    /Users/someuser/myprojects/myproject/node_modules/@react-native-community/async-storage/jest/async-storage-mock.js:6
    type KeysType = Array<string>;
         ^^^^^^^^

    SyntaxError: Unexpected identifier

Sure enough, when I inspect the async-storage-mock.js file at that path, it contains the type keywords, which I believe are the root cause of this issue.

What am I doing wrong here?


Solution

  • My solution was to switch to mock-async-storage

    My jestSetupFile.js:

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

    ^^ The above mocking code did not work when done at the beginning of my test scripts themselves, though my other mock code usually works there. This only worked when added to the jestSetupFile.js which I define in package.json:

    "jest:"  {
       "setupFiles": [
          "./jestSetupFile.js"
        ]
    }