Unit Testing Components with Jest in React Native. Setup and Trouble Resolutions
If you are interested in approaches for testing, read this article.
Setup:
1. Jest configuration
I removed properties not related to react-native (such as testMatch, testUrl, etc.)
Also, it could be jest.config.js (depends on your project organization)
2. Mocking store
I used redux-mock-store.
- For decrease duplicate code I’ve put it into __mocks__.
As example of middleware there is a thunk here. You could use any.
2. I’ve created a separate render component function.
3. And just use it:
3. Add more readable expect method “toBeFound”
- Create a script config/jest/expect.js
- Add it to setupFiles in your jest config
Trouble resolutions:
1. ES6 in node_modules
Error in using of es6+ libraries from node_modules such it:
/Users/dsitdikov/Projects/experimentx-dx-app/node_modules/react-native/jest/mockComponent.js:20 static displayName = ‘Component’; ^ SyntaxError: Unexpected token =
Solution:
Use transformIgnorePatterns in jest config:
By default jest transformIgnorePatterns has <rootDir>/node_modules and ignores all node_modules. So that it transforms each file from es6+ to understandable es5 except node_modules. Some modules are not in es6 and we should say ignore all node_modules except react-navigation, react-native, rn-apple-healthkit, etc.
2. Modules don’t work in jest.
Something like:
TypeError: Cannot read property ‘RNFSFileTypeRegular’ of undefined
> 4 | import RNFS from ‘react-native-fs’;
Solution:
It’s ok. Just:
- Create mocks.js in your project
- Add setupFiles in your jest configuration
3. For each unnecessary and unworking module write the following:
3. Error in using mocked default exported modules.
An error could be such this:
TypeError: Cannot read property ‘dirs’ of undefined
Solution:
Just add this to your mocks file.
If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇