The testing section of the docs for React Native suggest that Jest is the official way to do unit tests. However, they don't explain how to get it setup. Running Jest without any setup gives syntax errors (with no line numbers :( ) because it doesn't apply the transforms (eg ES6 features, JSX and Flow) that React Native code tends to use. There's a jestSupport
folder in the React Native source try that contains a env.js
and scriptPrerocess.js
, the latter has code for apply the transforms. So I've copied those into my project and added the following section to my package.json:
"jest": {
"scriptPreprocessor": "jestSupport/scriptPreprocess.js",
"setupEnvScriptFile": "jestSupport/env.js"
},
This fixes the first error but I still get the following error:
Using Jest CLI v0.4.0
FAIL js/sync/__tests__/SynchronisedStorage-tests.js
SyntaxError: /Users/tom/my-project/js/sync/__tests__/SynchronisedStorage-tests.js: /Users/tom/my-project/js/sync/SynchronisedStorage.js: /Users/tom/my-project/node_modules/react-native/Libraries/react-native/react-native.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/browser/ui/React.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/utils/ReactChildren.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/addons/ReactFragment.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/classic/element/ReactElement.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/core/ReactContext.js: /Users/tom/my-project/node_modules/react-native/node_modules/react-tools/src/vendor/core/warning.js: Unexpected token .
1 test failed, 0 tests passed (1 total)
Run time: 0.456s
Is there more I need to do to make Jest understand React Native? Are there any examples of Jest setup to test React Native?
EDIT:
There was a check in scriptPreprocess
that stopped it from running over any file in node_modules
which of course included the whole of React Native. Removing that fixes the error above. However, I'm now getting more errors from the React Native source, it definitely seems like it isn't meant to be run within Jest.
EDIT2:
Explicitly setting the mock for the react-native
module works:
jest.setMock('react-native', {});
That seems like it's going to be very manual and not very useful for testing code that interacts with the React Native API a lot. I definitely still feel like I'm missing something!
jestSupport
directory of which you speak? I'm not seeing it in a React-native 0.4 or 0.7 project. – pbanka