Currently, React Native dynamically requires a file for the running platform with an specific file extension, *.ios.js
or *.android.js
. However, when running this code inside a test environment, we get a require
error because the module require('./module')
cannot be found in the file tree, which looks like:
module.ios.js
module.android.js
How can we handle this issues in a test environment?
Note: Platform specific code can also be written by making use of the Platform module from react-native. import React, { Component } from 'react'; import { TextInput, View } from 'react-native'; import PropTypes from 'prop-types'; import styles from './TextArea.
React Native provides a module that detects the platform in which the app is running. You can use the detection logic to implement platform-specific code. Use this option when only small parts of a component are platform-specific.
The react-native mode is the equivalent of preserve in that it keeps all JSX, but the output will instead have a . js file extension.
React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows and UWP by enabling developers to use the React framework along with native platform capabilities.
Adding platform specific extensions to moduleFileExtensions
fixed the problem for me with jest.14.1
. Credits to : github link
Here is a snippet from sample package.json
which will run all files including scene.jest.js(x).
...
"jest": {
"verbose": true,
"preset": "jest-react-native",
"moduleFileExtensions": ["js", "android.js", "ios.js"],
"testRegex": "\\.scene\\.jest\\.jsx$"
}
...
As of Jest 17.0.0 you can use the defaultPlatform
configuration for this - see the very bottom of the Jest React Native tutorial.
As it shows there, you would configure something like this:
"haste": {
"defaultPlatform": "ios",
"platforms": ["android", "ios"],
},
Naturally, this will mean your tests only load the iOS version of your component (or only Android, depending how you choose to configure it).
If you find it important to test both versions, you'll probably need to do something more like the solution mentioned in this issue, possibly manipulating Platform.OS
and using require.requireActual
directly.
(Might also want to track this issue, in case a less hacky solution is eventually found.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With