问题
After using @react-native-community/async-storage and transpile it with the following npm command in my react-native environment.
"test": "NODE_ENV=test ./node_modules/.bin/mocha --timeout 5000 --require @babel/register \"./src/shared/__tests__/**/*.spec.js\""
I did some research and in no vain. But I found it happens to Jest too.
jest test fails after installing react-native-async-storage
this is my babel.config.js
module.exports = {
env: {
production: {
},
test: {
presets: [
'@babel/preset-env'
],
},
},
};
I'm only testing non-jsx code only so @babel/preset-env seems to be working alright.
node_modules/@react-native-community/async-storage/lib/index.js:5
import AsyncStorage from './AsyncStorage';
^^^^^^^^^^^^
SyntaxError: Unexpected identifier
回答1:
It seems like no one likes to answer jest newbie questions....
anyway, when starting to learn jest, I encountered some funny error messages that doesn't reflect the actual error. There are some possible situations a developer can consider.
- You didn't to mock your module say A_module that is inside node_modules so one of the modules say B_modules inside A_modules uses a NativeModules from react so Jest cannot performa a test. Please look at stack trace or use a debugger to find out which one you prefer to mock.
- Mock a module that uses NativeModules (similar to point 1, but more direct and concise )
- You need to understand jest more thoroughly before you proceed. Reading documentation is good but jump to example when you think fit. especially check out the examples that you really need and read related ones. Many of the time, either your Babel setting or mocking methods is incorrect.
- use jest.mock instead of jest.genMockFromModule. Why? there are some functions or init function that causes your test to crash at this statement. Because it calls NativeModules or something jest doesn't allow. use mock instead.
Solutions to this question: please refer to this most updated solution.
thanks
来源:https://stackoverflow.com/questions/56585037/async-storage-syntaxerror-unexpected-identifier-while-transpiling-with-babel7