Unit Testing Components with Jest in React Native. Setup and Trouble Resolutions

Daniil Sitdikov
2 min readApr 26, 2019

--

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.)

Code 1 — Fragment of package.json

Also, it could be jest.config.js (depends on your project organization)

2. Mocking store

I used redux-mock-store.

  1. For decrease duplicate code I’ve put it into __mocks__.

As example of middleware there is a thunk here. You could use any.

Code 2— Redux mock store located in __mocks__ folder

2. I’ve created a separate render component function.

Code 3— Receives component to render as content and state of the store

3. And just use it:

Code 4— Fragment of some component testing

3. Add more readable expect method “toBeFound”

Code 5 — Extension of expect-file
  1. Create a script config/jest/expect.js
  2. Add it to setupFiles in your jest config
Code 6 — Some test example

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:

Code 7— A fragment of the package.json > jest

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.

You also can read about it in jest documentation.

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:

  1. Create mocks.js in your project
  2. Add setupFiles in your jest configuration
Code 8 — Fragment of package.json > jest

3. For each unnecessary and unworking module write the following:

Code 9— An example of a mock some module

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.

Code 10— A fragment of mocks.js file

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

--

--