How to resolve a NativeModule.RNLocalize is null error in test? - react-native

I'm using the package react-native-localize to provide localization in an app. I've already linked the library and it works fine running on a device.
Issue:
When I test a component that imports react-native-localize. I get the error react-native-localize: NativeModule.RNLocalize is null.
In order to resolve this null error I call jest.mock('react-native-localize'); at the top of the test file. But I still get an error pointing to NativeModule.RNLocalize is null. I've also provided the mock as mentioned in the package README to no avail.
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
import * as RNLocalize from 'react-native-localize';
// mocking the module here with jest.mock
jest.mock('react-native-localize');
it('renders correctly', () => {
renderer.create(<App />);
});
Question:
How can you resolve a NativeModule.RNLocalize is null error in test?
Test Stack Trace:
FAIL __tests__/App-test.js
● Test suite failed to run
react-native-localize: NativeModule.RNLocalize is null. To fix this issue try these steps:
• Run `react-native link react-native-localize` in the project root.
• Rebuild and re-run the app.
• If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.
• Check that the library was linked correctly when you used the link command by running through the manual installation instructions in the README.
* If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README.
If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-localize
16 |
17 | import {NavigationContainer} from '#react-navigation/native';
> 18 | import * as RNLocalize from 'react-native-localize';
| ^
19 | import {Icon} from 'native-base';
20 | import {createStackNavigator} from '#react-navigation/stack';
21 | const Stack = createStackNavigator();
at Object.<anonymous> (node_modules/react-native-localize/lib/commonjs/module.js:17:9)
at Object.<anonymous> (node_modules/react-native-localize/lib/commonjs/index.js:3:1)
at Object.<anonymous> (src/modules/AppView.js:18:1)
at Object.<anonymous> (src/modules/AppViewContainer.js:2:1)
at Object.<anonymous> (App.js:23:1)
at Object.<anonymous> (__tests__/App-test.js:7:1)

I fixed this issue in my tests by adding these lines in my jest configuration file
jest.mock("react-native-localize", () => {
return {
getLocales: jest.fn(),
// you can add other functions mock here that you are using
};
});

I found the solution :- paste this code in your jest configuration file (setup.js)
jest.mock("react-native-localize", () => {
getLocales: jest.fn(), // use getLocales if you have used this, else use the one that you have used
// you can add other functions mock here that you are using
};
});

Related

jest test is not exiting after test passes with react-test-renderer

I have a toMatchSnapshot test on a simple component with React Native 0.68.2/jest 29.0. Here is the component SysError:
import React, {useState, useContext, Component} from 'react';
import {Platform, Button, Text, TouchableOpacity } from 'react-native';
export default function SysError({route}) {
const message = route.params.message;
return (
<Text>{message}. System NOT available right now. Try again later</Text>
)
};
Here is the SysError.test.js:
import React from 'react';
import renderer from 'react-test-renderer'; //<<==v17.0.2
import SysError from './SysError';
it ('describe SysError page view with no message', () => {
const route = {params: {message:"noth"}};
const tree = renderer.create(<SysError route={route} />).toJSON();
expect(tree).toMatchSnapshot();
})
After yarn test --detectOpenHandle, test passes but is not exiting by itself. Here is the error for component SysError:
Jest has detected the following 2 open handles potentially keeping Jest from exiting:
● MESSAGEPORT
1 | import React from 'react';
> 2 | import renderer from 'react-test-renderer';
| ^
3 | import SysError from './SysError';
4 |
5 | it ('describe SysError page view with no message', () => {
at node_modules/scheduler/cjs/scheduler.development.js:178:17
at Object.<anonymous> (node_modules/scheduler/cjs/scheduler.development.js:13:3)
at Object.require (node_modules/scheduler/index.js:6:20)
at require (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:19:19)
at Object.<anonymous> (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13:3)
at Object.require (node_modules/react-test-renderer/index.js:6:20)
at Object.<anonymous> (src/components/app/SysError.test.js:2:1)
at asyncGeneratorStep (node_modules/#babel/runtime/helpers/asyncToGenerator.js:3:24)
at _next (node_modules/#babel/runtime/helpers/asyncToGenerator.js:25:9)
There is no async call in SysError.js and what is missing here?
This seems to be caused by the scheduler package.
It was supposed to be fixed in React 17.1.0 but that never came around. There was even an issue for it.
What you can do, is any of the following:
Upgrade to React 18+ (Expo SDK 46+) and the corresponding RN version.
Use delete global.MessageChannel; which should do in your file where the issue is occurring.
Install the react-16-node-hanging-test-fix with yarn add react-16-node-hanging-test-fix or npm install react-16-node-hanging-test-fix which was made by a React core team member Dan Abramaov. This package essentially does step 2 with greater safety due to some checks and stuff.

NetInfo must be passed to networkMonitor to enable reachability in React Native

Getting below error for any snapshot testing where the component is using following import
import { Auth } from 'aws-amplify';
Test suite failed to run
NetInfo must be passed to networkMonitor to enable reachability in React Native
at ReachabilityNavigator.Object.<anonymous>.ReachabilityNavigator.networkMonitor (node_modules/#aws-amplify/core/src/Util/Reachability.native.ts:20:10)
at Object.<anonymous> (node_modules/#aws-amplify/datastore/src/sync/datastoreReachability/index.native.ts:4:55)
at Object.<anonymous> (node_modules/#aws-amplify/datastore/src/sync/datastoreConnectivity.ts:3:1)
If you go to the aws-aplify code, that error is thrown in this networkMonitor function, which is called in this other place where #react-native-community/netinfo is used. Mocking the dependency as indicated in the lib README should fix the issue.
If you do not have a Jest Setup file configured, you should add the
following to your Jest settings and create the jest.setup.js file in
project root:
setupFiles: ['<rootDir>/jest.setup.js']
You should then add the
following to your Jest setup file to mock the NetInfo Native Module:
import mockRNCNetInfo from '#react-native-community/netinfo/jest/netinfo-mock.js';
jest.mock('#react-native-community/netinfo', () => mockRNCNetInfo);

Unable to resolve module 'react-redux'...module 'react-redux' does not exist in haste module map

The code in app.js file with import statements for react redux is created to display a header with a text called "Tech stack".
App.js
import React from 'react';
import { View } from 'react-native';
import { Header } from './components/common';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './reducers';
const App = () => {
return(
<Provider store={createStore(reducers)}>
<View>
<Header headerText="Tech Stack" />
</View>
</Provider>
);
};
export default App;
This is the index file
index.js
import { AppRegistry } from 'react-native';
import App from './src/App';
AppRegistry.registerComponent(tech_stack, () => App);
While running this on the terminal, it throws a error saying unable to resolve module 'react-redux'.
Close the JS bundle(a terminal starts when you run app for first time) and rerun it using the command react-native start from the project path. Basically, you need to rerun the JS bundle after every package installation.
Install 'react-redux' by using
npm install --save react-redux
if you not installed it. By seeing your comment as you mentioned that you installed redux only.
Then restart the JS bundle by using
react-native start --reset-cache
I've faced this issue just now. actually, Our (you and I) main issue is naming the global state folder name is redux and the bundler falls in a conflict because there is a folder inside node_modules that name is redux too.
In fact, the main issue is this line:
import { createStore } from 'redux';
I renamed the resux stuffs folder to reduxStore instead of redux and then everything works properly.
This error occurs because you do not have Redux-Thunk middleware installed on your application. To install run:
npm install redux-thunk
Then, restart your application:
react-native start
More information: https://github.com/reduxjs/redux-thunk
I just ran into this problem and solved it by installing redux in addition to react-redux. Apparently, react-redux requires it.

How to mock react native I18nManager

I am trying to run jest cases in react native. I am using react-native-router-flux for navigation. My test cases are being failed with this error
Test suite failed to run
TypeError: Cannot read property 'isRTL' of undefined
at Object.<anonymous> (node_modules/react-native-router-flux/dist/NavBar.js:286:44)
at Object.<anonymous> (node_modules/react-native-router-flux/dist/navigationStore.js:7:13)
at Object.<anonymous> (node_modules/react-native-router-flux/dist/Reducer.js:74:36)
Exact line is transform:[{scaleX:_reactNative.I18nManager.isRTL?-1:1}]})
I tried different ways to mock but could not get it
One method is
import {I18nManager} from 'react-native'
I18nManager = {
isRTL : false
}
I put this snippet in jest initial configuration file but I got error like I18nManager is readonly
Actually I am using an explicit module factory that is being run instead of using Jest's automocking feature which is react-native-mock-render .
Like this
jest.mock('react-native', () => require('react-native-mock-render'), {
virtual: true
})
When I go through this lib code I could not found I18nManager in the mocks. So I forked that repo and added I18nManager file myself.

How to mock react-native module (not 3rd party module) with jest

I am trying to mock a module that ships with react-native (not 3rd party modules), such as LayoutAnimation:
import * as RN from 'react-native'
RN.LayoutAnimation = jest.fn()
But the test fails with:
TypeError: Cannot read property 'decelerationRate' of undefined
at Object.<anonymous> (node_modules/react-native/Libraries/Components/WebView/WebView.ios.js:555:3254)
at Object.get WebView [as WebView] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:73:22)
Is there any other way to mock/stub out a RN module such as LayoutAnimation or any other react-native (not 3rd party) module?
Try to simply do jest.mock('LayoutAnimation');
You got this message because of line №217 in /node_modules/react-native/Libraries/Components/WebView/WebView.ios.js
decelerationRate: ScrollView.propTypes.decelerationRate
Because ScrollView is mocked ScrollView.propTypes === undefined
I solved this issue by adding:
import {PropTypes} from 'react';
ScrollView.propTypes = { decelerationRate: PropTypes.number };
to setup script file (file which set by setupTestFrameworkScriptFile property in jest section of package.json);