Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
lance.dolan Avatar asked Jan 27 '23 07:01

lance.dolan


2 Answers

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"
    ]
}
like image 68
lance.dolan Avatar answered Jan 30 '23 05:01

lance.dolan


As of 2022, you can do that with community package @react-native-community/async-storage recommended by React-Native official documentation

Everything is explain in their doc

  1. In your Jest config (probably in package.json) add setup files location:
"jest": {
  "setupFiles": ["./path/to/jestSetupFile.js"]
}
  1. Inside your setup file, set up Async Storage mocking:
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';
    
jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);
like image 28
Kruupös Avatar answered Jan 30 '23 04:01

Kruupös