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?
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"
]
}
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
"jest": {
"setupFiles": ["./path/to/jestSetupFile.js"]
}
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';
jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With